Processing color collision detection (java) - java

I have to make a tron type game with collision detection. I started by making p1 and p2 move and leave a trail behind them.
I tried to make a color collision detection but its not working. I have different variables such as "P1_edge" which is when p1 hits the edge of the screen. I mark that with a red border.
But the only one that seem to be working is when they crash into themselves when the game starts. It instantly finishes as they are already on themselves. if I take that bit away, nothing else detects.
int P1_XPos; //Player 1 position
int P1_YPos;
boolean Player1_Up = false; //Determins what way P1 is going
boolean Player1_Down = false;
boolean Player1_Left = false;
boolean Player1_Right = true;
int P2_XPos; //Player 2 position
int P2_YPos;
boolean Player2_Up = false; //Determins what way P2 is going
boolean Player2_Down = false;
boolean Player2_Left = true;
boolean Player2_Right = false;
boolean Game_State = false; //see if the game is over (false = over)
final int P1_Edge = 0; //P1 crashed into the edge
final int P1_P1 = 1; //P1 crashed into P1
final int P1_P2 = 2; //P1 crashed into P2
final int P2_Edge = 3; //P2 crashed into the edge
final int P2_P2 = 4; //P2 crashed into P2
final int P2_P1 = 5; //P2 crashed into P1
final int Crash = 6; //Other
void setup()
{
size(700,600); //Set screen dimensions
background(0, 0, 0);
P1_XPos = 100; //set P1 and P2 posision
P1_YPos = 100;
P2_XPos = 600;
P2_YPos = 500;
strokeWeight(3); //Draw the edge of the screen
stroke(255, 0, 0);
line(1, 1, 1, height - 1);
line(1, 1, width - 1, 1);
line(width - 2, 1, width - 2, height - 1);
line(1, height - 2, width - 1, height - 2);
stroke(0, 255, 0); //Draw the starting positions
point(P1_XPos, P1_YPos);
stroke(0, 0, 255);
point(P2_XPos, P2_YPos);
}
void draw()
{
strokeWeight(3);
if (Game_State == true) //if the game is not over
{
stroke(0, 255, 0); //Draw P1
point(P1_XPos, P1_YPos);
MovePlayer1(); //Move P1
stroke(0, 0, 255); //Draw P2
point(P2_XPos, P2_YPos);
MovePlayer2(); //Move P2
Collision_Detection(); //Detect any crashes
}
}
void keyPressed()
{
if(key == CODED) //Controls P1 movement
{
if (keyCode == UP)
{
Player1_Up = true;
Player1_Down = false;
Player1_Left = false;
Player1_Right = false;
}
else if(keyCode == DOWN)
{
Player1_Down = true;
Player1_Up = false;
Player1_Left = false;
Player1_Right = false;
}
else if (keyCode == LEFT)
{
Player1_Left = true;
Player1_Down = false;
Player1_Up = false;
Player1_Right = false;
}
else if (keyCode == RIGHT)
{
Player1_Right = true;
Player1_Down = false;
Player1_Left = false;
Player1_Up = false;
}
}
if ((key == 'W') || (key == 'w')) //Controls P2 movement
{
Player2_Up = true;
Player2_Down = false;
Player2_Left = false;
Player2_Right = false;
}
else if((key == 'S') || (key == 's'))
{
Player2_Down = true;
Player2_Up = false;
Player2_Left = false;
Player2_Right = false;
}
else if ((key == 'A') || (key == 'a'))
{
Player2_Left = true;
Player2_Down = false;
Player2_Up = false;
Player2_Right = false;
}
else if ((key == 'D') || (key == 'd'))
{
Player2_Right = true;
Player2_Down = false;
Player2_Left = false;
Player2_Up = false;
}
if (key == ' ')
{
Game_State = true;
}
}
void MovePlayer1() //Moves P1
{
if(Player1_Up == true)
{
P1_YPos -= 1;
}
if(Player1_Down == true)
{
P1_YPos += 1;
}
if(Player1_Left == true)
{
P1_XPos -= 1;
}
if(Player1_Right == true)
{
P1_XPos += 1;
}
}
void MovePlayer2() //Moves P2
{
if(Player2_Up == true)
{
P2_YPos -= 1;
}
if(Player2_Down == true)
{
P2_YPos += 1;
}
if(Player2_Left == true)
{
P2_XPos -= 1;
}
if(Player2_Right == true)
{
P2_XPos += 1;
}
}
int TestColorP1 (color P1Test) //Detect what color P1 is touching
{
if (P1Test == color (255,0,0))
return P1_Edge;
else if (P1Test == color(0,255,0))
return P1_P1;
else if (P1Test == color(0,0,255))
return P1_P2;
else return Crash;
}
int TestColorP2 (color P2Test) //Detect what color P2 is touching
{
if (P2Test == color (255,0,0))
return P2_Edge;
else if (P2Test == color(0,255,0))
return P2_P1;
else if (P2Test == color(0,0,255))
return P2_P2;
else return Crash;
}
void Collision_Detection()
{
color P1_Pixel; //This is the color P1 is touching
color P2_Pixel;
P1_Pixel = get(P1_XPos, P1_YPos); //Declare is as P1 position
P2_Pixel = get(P2_XPos, P2_YPos);
if (TestColorP1(P1_Pixel) == P1_Edge) //See if P1 has crashed
{
background(0);
Game_State = false;
}
else if (TestColorP1(P1_Pixel)== P1_P1)
{
// background(0);
// Game_State = false;
}
else if (TestColorP1(P1_Pixel) == P1_P2)
{
background(0);
Game_State = false;
}
if (TestColorP2(P2_Pixel) == P2_Edge) //See if P2 has crashed
{
background(0);
Game_State = false;
}
else if (TestColorP2(P2_Pixel)== P2_P1)
{
background(0);
Game_State = false;
}
else if (TestColorP2(P2_Pixel) == P2_P2)
{
// background(0);
// Game_State = false;
}
else if (TestColorP2(P2_Pixel) == Crash)
{
}
}
I know it's long, but you should be able to just copy and paste this in a processing sketch and it will work. I have also left comments so you know why I've added each bit of code.

This was a real head scratcher- good question.
The biggest thing throwing you off is the fact that Processing enables anti-aliasing by default. This causes your colors to be just a little different than what you expect. In most sketches, this is a good thing, since it makes things look better. But since you're using the exact color values, this is screwing you up. You can prove this by taking a screenshot of your sketch and then sampling your colors.
To disable this, simply call noSmooth() at the beginning of your sketch. More info can be found in the reference here.
The next thing screwing you up is that your stroke weight is set to 3, but you're only moving the players 1 pixel at a time. This causes the players to stay "inside" the last point that was drawn, which is why they're constantly running into themselves.
To fix that, you could simply call strokeWeight(1); at the beginning of the draw() function. Or if you need a stroke weight of 3, then make sure you move the player outside of the circle that was just drawn.
That'll fix your problem here, but in the long run, you'd probably be better off keeping track of previous player positions in a data structure like an ArrayList of PVectors. Then you'd redraw them each time draw() was called instead of only drawing them once. And instead of trying to check colors manually, it would be easier to do collision checks in only certain parts of the paths, to avoid the above case.

Related

Intersect function stops working after the first intersect

im making a game, but i ran into a problem while working with the function "intersect".
the senario looks like this; i've made a game where the player is a rectangle were the objective is to kill the enemy rectangle. The enemy "boss" rectangle has two "simulations" that simulate a movement and an attack these simulations are driven by vectors. The movement is horizantally back and forth and the attack is in a vertical maner, a charge type of deal. The boss also has a rectangular target area where if itersected the "boss" will charge across the screen.
now the problem comes when i tried to make it so that if the player intersects with the rectangular target area the "boss" will attack/charge. The boss attack/charge the first time the player intersects but not after that. I want the boss to follow the same pantern, is that he should only be able to go from side to side horizantaly and if Target area intersected; attack/charge verticaly.
( i will include some code bellow. sorry if my english is bad. )
first comes the main:
boss b;
Character C;
void setup(){
C = new Character();
b = new boss();
}
void draw(){
if (play) {
b.simulate(); //horizantal movement
}
if (b.start) {
b.sim(); //boss vertical attack
}
if (b.intersects(C)){
play = false;
b.start = true;
}
C.character(); //player
b.bounce(); //makes it bounce if horizantal. and stop if vertical
b.Display(); //boss
b.display(); //boss target area
}
Next comes the boss:
class boss {
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boss() {
Location = new PVector( x+25, y ); //vector for the location of the boss
Velocity = new PVector( 5, 0 ); // vector for horizaltal movement
speed = new PVector( 0, 10 ); // vector for vertical down movement
speed2 = new PVector(0, -10); // vector for vertical up movement
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) { //horizantal movement bounce on screen edge
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
start = false; //makes boss stop if reaches botton or top of the screen
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false; //specificly if it reaches top of screen
}
if (Location.y == 0) {
RH = 700;
down = true; //specificly if it reaches bottom of screen
up = false;
}
}
}
void simulate() {
Location.add(Velocity); //simulates horizantal movement
}
void sim() {
if (down) {
Location.add(speed); //simulates up and down attacking movemnet
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
return Location.x < C.x + C.w && C.x < Location.x + RW &&
Location.y < C.y + C.h && C.y < Location.y + RH; //intersect between player and boss targeting area
}
void Display() {
rect( Location.x, Location.y, 50, 50 ); //boss
}
void display() {
rect( Location.x, Location.y+50, RW, RH ); //boss targeting area
}
}
if anything is unclear i will gladly clear up any confusion. :)
Thanks for sharing the code. It made it much easier.
When I comment this piece (not the if-condition the reset of start after the if)
if ((Location.y == 650) || (Location.y == 0)) {
// start = false;
then the boss starts going back up top and still calls intersects the Character when the co-ordinates match. However, post this the boss keeps bouncing up and down.
There is surely more work to be done on this to take account of the bullets fired and the hits to boss.
Hope this helps. :) It was fun debugging this code. I had never used PDE before this.
ok, here is the "edit"..
Now,
Good News: I can make it go in both directions only when it intersects
Bad News: It keeps going to the other side as long as it is intersecting. So if the Character is stationary then boss keeps intersecting and passing to the other side at least 8-10 times in the current speed.
Anyways, here is the summary. I added and isAttacking flag that tells the program to not stop the boss from crossing over if it has reached the bottom of the frame. The other thing I changed was the intersection condition. Now it just checks for intersection on the X-Axis. If you must compare intersection on the Y-Axis too then intersects is where you need to change & test.
After the long explanation :P Here is the code. Hope this is better.
Main
boss b;
Character C;
Inventory I;
Bullet B;
int previousKey = 0;
int lastKey;
int lastKeyCode;
void setup() {
C = new Character();
b = new boss();
I = new Inventory();
background(128, 128, 128);
size( 700, 700 );
strokeWeight( 10 );
frameRate( 30 );
}
void keyPressed() {
if (key == CODED) {
previousKey = keyCode;
if (keyCode == UP) {
C.MoveUP();
}
if (keyCode == LEFT) {
C.MoveLEFT();
}
if (keyCode == DOWN) {
C.MoveDOWN();
}
if (keyCode == RIGHT) {
C.MoveRIGHT();
}
}
if (key == 'w' || key == 'W') {
attack();
}
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B = new Bullet(C.x, C.y);
this.Shoot();
}
} else if (key == 'e' || key == 'E') {
I.changePop();
}
if (keyPressed) {
if (key == 'a' || key == 'A') {
//play = false;
//b.start = true;
}
}
}
void attack() {
if (I.Attack == true) {
if (previousKey == UP) {
C.AttackUP();
}
if (previousKey == LEFT) {
C.AttackLEFT();
}
if (previousKey == DOWN) {
C.AttackDOWN();
}
if (previousKey == RIGHT) {
C.AttackRIGHT();
}
}
}
void Shoot() {
if (I.Shoot == true) {
if (previousKey == UP) {
B.ShootUP();
}
if (previousKey == LEFT) {
B.ShootLEFT();
}
if (previousKey == DOWN) {
B.ShootDOWN();
}
if (previousKey == RIGHT) {
B.ShootRIGHT();
}
}
}
boolean play = true;
void keyReleased() {
lastKey = 0;
lastKeyCode = 0;
}
void draw() {
background(128, 128, 128);
if (play) {
b.simulate();//side to side
}
if (b.start) {
b.sim(); //boss rush
}
if (b.intersects(C)) {
b.isAttacking = true;
play = false;
b.start = true;
} else {
b.isAttacking= false;
}
C.character();
b.bounce();
b.Display();//boss
b.display();//rush area
C.HPbar();
I.popUp();
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B.bullet();
B.Simulate();
}
}
}
Enemies or Boss
class boss {
PVector Location;
PVector Velocity;
PVector speed;
PVector speed2;
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boolean isAttacking = false;
boss() {
Location = new PVector( x+25, y );
Velocity = new PVector( 5, 0 );
speed = new PVector( 0, 10 );
speed2 = new PVector(0, -10);
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) {
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
if (!isAttacking) {
start = false;
}
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false;
}
if (Location.y == 0) {
RH = 700;
down = true;
up = false;
}
}
}
void simulate() {
Location.add(Velocity);
}
void sim() {
//print("\n In Sim UP: [" + up + "] Down: [" + down + "] Location [" + Location + "]");
if (down) {
Location.add(speed);
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
//print ("\nUP: [" + up + "] Down: [" + down + "] X: [" + (Location.x < (C.x + C.w) && (Location.x + RW) > C.x)
//+ "] Y: [" + (Location.y < (C.y + C.h) && (Location.y + RH) > C.y) + "]");
return Location.x < (C.x + C.w) && (Location.x + RW) > C.x;
//&&
// Location.y < (C.y + C.h) && (Location.y + RH) > C.y ;
}
void Display() {
pushStyle();
stroke(0);
fill(255, 0, 0);
rect( Location.x, Location.y, 50, 50 );
popStyle();
}
void display() {
pushStyle();
stroke(0);
strokeWeight(0);
fill(255, 0, 0, 20);
rect( Location.x, Location.y+50, RW, RH );
popStyle();
}
}

JAVA acm getBound.intersects doesn't work properly?

Hey so i have to make this game, basically a ball (bug) needs to change directions once it hits other objects, (rectangles and objects)
Im using getBounds.intersects to see if it hits the objects or not, but it doesn't work if the ball goes from right to left. Basically any object it hits going from right to left it just goes through which causes the game to get stuck eventually, but any other directions work just fine.
here is my code
package week6Homework;
import java.awt.Color;
import java.awt.Frame;
import java.util.Random;
import acm.graphics.GOval;
import acm.graphics.GRect;
import acm.graphics.GRectangle;
import acm.program.*;
public class BugBotTry1984756212 extends GraphicsProgram
{
//constants for screen specs
final int WIN_HEIGHT = 900;
final int WIN_WIDTH = 1900;
//booleans for turns
boolean turn;
boolean left;
boolean right;
boolean down;
boolean up;
//creating bugbot itself using external class
BugBot bug = new BugBot();
//creating arrays for ovals and rectangles
GOval[] ovals = new GOval[4];
GRect[] rects = new GRect[4];
//this is a string array that will bre sued to figure out what if the bugbot
//needs to go up/down or left/right
//its hard to explain what this does but you will figure it out later in the code
String[] horizontalTurn = new String [2];
String[] verticalTurn = new String[2];
public void init()
{
//setting name of the applet
Frame title = (Frame)this.getParent().getParent();
this.setTitle("BugBotField");
//set screen specs
setSize(WIN_WIDTH, WIN_HEIGHT);
}//init
public void run()
{
//using methods to create the rectangles and ovals and bugbot
createOvals();
createRects();
add(bug, 100, 450);
//asigning words to the horizontal string array
horizontalTurn[0] = "down";
horizontalTurn[1] = "up";
verticalTurn[0] = "right";
verticalTurn[1] = "left";
//assigning values to boolean variables to see where the bug should move
//basivally if the right = true the bugbot will be moving right, and if down is true
//and the rest of them are false the bugbot will be moving down.
right = false;
left = true;
down = false;
up = false;
//main while loop that checks everything nad does everything
while (true)
{
//pause so the game doesn't end within one second after start.
pause(10);
if (right == true)
{
bug.move(5, 0);
}
else if (left == true)
{
bug.move(-5, 0);
}
else if (down == true)
{
bug.move(0, 5);
}
else if (up == true)
{
bug.move(0, -5);
}
//get X and Y coordinates for the bugbot so it wont go out of boundaries.
int bugX = (int)bug.getX();
int bugY = (int)bug.getY();
//for loop to check colossion detection.
//basically for every time the while loop runs (which is every .1 seconds because of our pause)
//it will run this for loop 4 times (because thats how many objects we have in our arrays
// and we are using array.length to see how many times the for loop needs to run
for (int i = 0; i < rects.length; i++)
{
//integer that gets bounds of all rectangles in the array.
GRectangle rectangleBounds = rects[i].getBounds();
//making 3 of those since if the bug hits the last red circle we need
//the game to stop and not turn directions.
// i could do it differently but didn't feel like redoing bunch of stuff so here.
GRectangle ovalBounds1 = ovals[0].getBounds();
GRectangle ovalBounds2 = ovals[1].getBounds();
GRectangle ovalBounds3 = ovals[2].getBounds();
GRectangle ovalBounds = ovals[i].getBounds();
//check for collision with other objects
if (bug.getBounds().intersects(rectangleBounds) || bug.getBounds().intersects(ovalBounds))
{
//check for collision if direction is "right"
if (right == true && left == false && down == false && up == false)
{
for (int x = 3; x >= 0; x--)
{
pause (50);
bug.move(-2, 0);
}
String direction = getRandom(horizontalTurn);
right = false;
left = false;
down = false;
up = false;
if (direction == "up")
{
up = true;
}
else if (direction == "down")
{
down = true;
}
}
//check for collision if direction is "left"
else if (left == true && right == false && right == false && left == false)
{
for (int x = 3; x >= 0; x--)
{
pause (50);
bug.move(2, 0);
}
String direction = getRandom(horizontalTurn);
right = false;
left = false;
down = false;
up = false;
if (direction == "up")
{
up = true;
}
else if (direction == "down")
{
down = true;
}
}
//check for collision if direction "down"
else if (down = true && up == false && right == false && left == false)
{
for (int x = 3; x >= 0; x--)
{
pause (50);
bug.move(0, -2);
}
String direction = getRandom(verticalTurn);
right = false;
left = false;
down = false;
up = false;
if (direction == "right")
{
right = true;
}
else if (direction == "left")
{
left = true;
}
}
//check for collision if direction "up"
else if (up == true && down == false && right == false && left == false)
{
for (int x = 3; x >= 0; x--)
{
pause (50);
bug.move(0, 2);
}
String direction = getRandom(verticalTurn);
right = false;
left = false;
down = false;
up = false;
if (direction == "right")
{
right = true;
}
else if (direction == "left")
{
left = true;
}
}
}//if for collision with objects
else if (bugX >= WIN_WIDTH)
{
right = false;
left = true;
down = false;
up = false;
}
else if (bugX <= 0)
{
right = true;
left = false;
down = false;
up = false;
}
else if (bugY >= WIN_HEIGHT)
{
down = false;
up = true;
}
else if (bugY <= 0)
{
up = false;
down = true;
}
}
}
}
public void createOvals()
{
GOval orange = new GOval(400,100,200,200);
GOval green = new GOval(100,550,300,250);
GOval red = new GOval(1500,450,125,125);
GOval blue = new GOval(1650,150,200,200);
ovals [0] = orange;
ovals [1] = green;
ovals [2] = blue;
ovals [3] = red;
ovals[0].setFilled(true);
ovals[0].setColor(Color.ORANGE);
add(ovals[0]);
ovals[1].setFilled(true);
ovals[1].setColor(Color.GREEN);
add(ovals[1]);
ovals[2].setFilled(true);
ovals[2].setColor(Color.BLUE);
add(ovals[2]);
ovals[3].setFilled(true);
ovals[3].setColor(Color.RED);
add(ovals[3]);
}//creating ovals method
public void createRects()
{
GRect green = new GRect(1000,0,250,250);
GRect green2 = new GRect(650,400,250,100);
GRect RedR = new GRect(1300,700,300,250);
GRect BlueR = new GRect(450,750,250,250);
rects [0] = green;
rects [1] = green2;
rects [2] = RedR;
rects [3] = BlueR;
rects[0].setFilled(true);
rects[0].setColor(Color.GREEN);
add(rects[0]);
rects[1].setFilled(true);
rects[1].setColor(Color.GREEN);
add(rects[1]);
rects[2].setFilled(true);
rects[2].setColor(Color.RED);
add(rects[2]);
rects[3].setFilled(true);
rects[3].setColor(Color.BLUE);
add(rects[3]);
}//create rectangles method
public static String getRandom(String[] array)
{
int rnd = new Random().nextInt(array.length);
return array[rnd];
}//getRandom
}
please help, thank you.
P.S. my BugBot bug is an external class i created, now sure if it matters what i have in there. But if it does ill add it later on.
Since all other directions are working fine, the problem can't be with the intersects function.
This if statement will never be true, since you're comparing left to both true and false.
//check for collision if direction is "left"
else if (left == true && right == false && right == false && left == false)
I think you want
else if (left == true && right == false && up == false && down == false)

how to make my player move in diagonal lines and horizontal lines

i have the following code to make an ellipse move to the left right top and bottom. but now the player can only move in one direction at the time. so if the player moves to the left he cant move to the to the top or bottom. how do i make my code so the player can move both left and right and to the top and the bottom at the same time? any suggestions are appreciated. :)
see the code that i have so far:
void userInput() {
if (keyPressed && (key == 's')) {
speedY = 1;
println("yes");
}
if (keyPressed && (key == 'w')) {
speedY = -1;
println("yes");
}
if (keyPressed && (key == 'd')) {
println("yes");
speedX = 1;
}
if (keyPressed && (key == 'a')) {
println("yes");
speedX = -1;
}
if (keyPressed &&(key != 'a' && key != 'd')) {
println("no");
speedX = 0;
}
if (keyPressed &&(key != 'w' && key != 's')) {
println("no");
speedY =0;
}
}
void movement() {
x = x + speedX;
y = y + speedY;
}
One way to do this is to use boolean values to keep track of which keys are pressed. Set them to true in keyPressed(), set them to false in keyReleased(), and use them to move your actor in the draw() function.
boolean upPressed = false;
boolean downPressed = false;
boolean leftPressed = false;
boolean rightPressed = false;
float circleX = 50;
float circleY = 50;
void draw() {
background(200);
if (upPressed) {
circleY--;
}
if (downPressed) {
circleY++;
}
if (leftPressed) {
circleX--;
}
if (rightPressed) {
circleX++;
}
ellipse(circleX, circleY, 20, 20);
}
void keyPressed() {
if (keyCode == UP) {
upPressed = true;
}
else if (keyCode == DOWN) {
downPressed = true;
}
else if (keyCode == LEFT) {
leftPressed = true;
}
else if (keyCode == RIGHT) {
rightPressed = true;
}
}
void keyReleased() {
if (keyCode == UP) {
upPressed = false;
}
else if (keyCode == DOWN) {
downPressed = false;
}
else if (keyCode == LEFT) {
leftPressed = false;
}
else if (keyCode == RIGHT) {
rightPressed = false;
}
}
(source: happycoding.io)
More info can be found in this tutorial on user input in Processing.

Ball going through paddle when increasing velocity

I am trying to create a Pong game and so far I have everything working for me other than the ball. At first I had the ball's x and y axis move up by one space each time. It was working fine until i decided to increase it to 2. I cant figure out what is wrong with my code and I need help.
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JPanel implements KeyListener{
int x = 90;
int y = 90;
int rectytop = 30;
int rectytop2 = 30;
int rectybottom = rectytop + 100;
int rectybottom2 = rectytop2 + 100;
int border = 30;
boolean balldown = true;
boolean ballright = true;
boolean playerborderup = false;
boolean playerborderdown = false;
boolean balltouch1 = false;
boolean balltouch2 = false;
private void moveball() {
if (balldown == true){
y = y + 2;
}
if (y == getHeight()-border){
balldown = false;
}
if (balldown == false){
y = y - 2;
}
if (ballright == true){
x = x + 2;
}
if (x == getWidth()-border){
ballright = false;
}
if (ballright == false){
x = x - 2;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
if (balltouch1 == false){
if (x == 75){
if(y < rectybottom && y > rectytop){
ballright = true;
}
}
}
if (balltouch2 == false){
if (x == 390 && y < rectybottom2 && y > rectytop2){
ballright = false;
}
}
}
#Override
public void paint(Graphics g){
super.paint(g);
//drawing ball and paddles
g.fillOval(x, y, 30, 30);
g.fillRect(45 , rectytop, 30, 100);
g.fillRect(425, rectytop2, 30, 100);
}
public static void main(String[] args) throws InterruptedException {
//making the window
JFrame f = new JFrame("Pong Game");
Pong game = new Pong();
f.setVisible(true);
f.setSize(500, 500);//1024, 724
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(game);
//game code
f.add(game);
while (true){
game.repaint();
game.moveball();
Thread.sleep(10);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
//player one
if (e.getKeyCode() == KeyEvent.VK_W){
if (rectytop == 0){
playerborderup = true;
}
if (rectytop != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop = rectytop + 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderup == false){
rectytop = rectytop - 5;
rectybottom = rectytop + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_S){
if (rectytop == 585){
playerborderdown = true;
}
if (rectytop != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop = rectytop - 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderdown == false){
rectytop = rectytop + 5;
rectybottom = rectytop + 100;
repaint();
}
}
//player two
if (e.getKeyCode() == KeyEvent.VK_UP){
if (rectytop2 == 0){
playerborderup = true;
}
if (rectytop2 != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop2 = rectytop2 + 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderup == false){
rectytop2 = rectytop2 - 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
if (rectytop2 == 585){
playerborderdown = true;
}
if (rectytop2 != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop2 = rectytop2 - 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderdown == false){
rectytop2 = rectytop2 + 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Since you are moving by 2 every time, it may "skip" over some coordinates. Thus when you say
if (y == getHeight()-border){
balldown = false;
}
y might go from getHeight()-border + 1 to getHeight()-border - 1 and never meet this condition. Thus, change it to a range or a less than. Your new code should be
if (y <= getHeight()-border +1){
balldown = false; //change the +1 and -1 to have difference at least speed number
}
Note that you must do the same for the other ifs with ==, change
if (x == getWidth()-border){
ballright = false;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
to
if (x <= getWidth()-border +1){
ballright = false;
}
if (y <= 1){
balldown = true;
}
if (x <= 1){
ballright = true;
}
Note that you can resolve the problem also by saying if the position is eer exactly one away from the border, temporarily decrement position by 1 instead of 2.
You are using if (x == 75) to detect collision with the left paddle. But if speed is 2 than the ball's x is always even and never equals 75. For a quick fix, check x against a range: if (x > 60 && x < 75)

Processing My sprite wont move

could you help me to make my sprite walk left and right ? i just cant see where the problem is.
I've spend 3 hours looking at the code but i just cant see where i've made mistake ...
class Player {
PImage playerr;
PVector position;
PVector velocity;
float direction;
float speed;
float ground = 600;
float left;
float right;
Player()
{
playerr = loadImage("sir1.png");
position = new PVector(400, ground);
direction = 1;
speed = 4;
velocity = new PVector(0, 0);
}
void update()
{
velocity.x = speed * (left + right);
PVector nextPosition = new PVector(position.x, position.y);
pushMatrix();
translate(position.x, position.y);
scale(direction, 1);
image(playerr, 0, 0);
popMatrix();
}
void keyPressed()
{
if (key == RIGHT)
{
right += 5;
direction = -1;
}
if (key == LEFT)
{
left -= 5;
direction = 1;
}
}
void keyReleased()
{
if (key == RIGHT)
{
right = 0;
}
if (key == LEFT)
{
left = 0;
}
}
}
and that's the main program
int stage;
PFont startfont;
PFont normalfont;
PImage gameplan;
boolean[] keys = new boolean[526];
ArrayList knight;
void setup()
{
size(800,800);
frameRate(60);
stage = 1;
knight = new ArrayList();
smooth();
}
void draw()
{
switch(stage)
{
case 1:
splash();
break;
case 2:
game();
break;
case 3:
help();
break;
case 4:
help();
break;
}
}
void game()
{
gameplan = loadImage("background.png");
gameplan.resize(800,800);
background(gameplan);
knight.add(new Player());
for(int i = 0; i <knight.size(); i++)
{
Player p = (Player) knight.get(i);
p.update();
}
}
void splash()
{
background(0);
startfont = createFont("start.ttf",40);
normalfont = createFont("start.ttf",25);
textFont(startfont);
text("Zombie Destruction",100,300);
textFont(normalfont);
text("Press Space to start",200,400);
text("Press H for help",250,500);
if(keyPressed)
{
if(key == 'h' || key == 'H')
{
stage = 4;
}
}
if(keyPressed)
{
if(key == ' ')
{
stage = 2;
}
}
}
void help()
{
background(0);
startfont = createFont("start.ttf",40);
normalfont = createFont("start.ttf",25);
textFont(normalfont);
text("Zombie Destruction",100,300);
textFont(normalfont);
text("Press Space to go back",200,400);
if(keyPressed)
{
if(key == 'b')
{
stage = 1;
}
else
{
stage = 4;
}
}
}
I believe the problem is in the Player class's update() method. It looks like you're calculating the updated velocity, but you never add that velocity to the player's position. A simple
position.x += velocity.x;
should do the trick.

Categories