How can I solve this collision detection bug? - java

In this code i'm trying to make collision detection between the Enemy (that is constantly moving)and the Player. I set so that the Enemy will go in the oposite direction when hit. But when the two hit each other from different directions, there is a bug: the Enemy gets stuck in the Player until I move him. I know that instead of moving in the oppoite direction, I should change so it goes away from the Player, but I don't know how. Please help me!
public Enemy(float x, float y, ID id, Handler handler) {
super(x, y, id);
this.handler = handler;
vely = -6;
velx = -6;
}
protected void tick(LinkedList<Object> object) {
x += velx;
y += vely;
if(x <= 0){
if(velx < 0) velx = velx * -1;
}
if(y <= 0) {
if(vely < 0) vely = vely * -1;
}
if(x >= 605){
if(velx > 0) velx = velx * -1;
}
if(y >= 418) {
if(vely > 0) vely = vely * -1;
}
collision();
}
private void collision() {
for(int i = 0; i < handler.object.size(); i++) {
Object obj = handler.object.get(i);
if(obj.getId()== id.Player) {
if(getBound().intersects(obj.getBound())) {
velx = velx * -1;
vely = vely * -1;
}
}
}
}
protected void render(Graphics g) {
g.setColor(Color.BLACK);
g.fillOval((int)x, (int)y, 30, 30);
}
public Rectangle getBound() {
return new Rectangle((int)x, (int)y, 30, 30);
}

If the enemy is to the left of the player, set the enemy’s velx to negative, otherwise positive. Similarly for vely if enemy is above the player.
// on collision...
velx = Math.abs(velx);
vely = Math.abs(vely);
if ( enemy_left_of_player() )
velx = -velx;
if ( enemy_above_player() )
vely = -vely;
Exact left/above logic will depend on size of player (is it also 30 pixels?)

Related

jumping and moving in processing

I am trying to get a circle to be able to jump and move left and right at the same time, but right now its either only jumping or moving forward at a time. Anyone know how to change my code to solve this? Thanks
float px,py,vx,vy,ax,ay;
boolean canJump = false;
void setup(){
size(600, 400);
ax = 0;
ay = .32;
vx = 0;
vy = 0;
px = 300;
py = 200;
}
int x = 50;
int y = 520;
void draw(){
background(0);
ellipse(px-15, py-30, 60, 60);
vx+=ax;
vy+=ay;
px+=vx;
py+=vy;
if( py > height ){
py = height;
vy = 0;
canJump = true;
}
player();
}
void player(){
fill(255);
rect(0, 550, 1000, 50);
}
void keyPressed(){
if(keyCode == RIGHT || key == 'd'){
px += 10;
}
if(keyCode == LEFT || key == 'a'){
px -= 10;
}
if(keyCode == UP){
if(canJump) {
vy = -10;
canJump = false;
}
}
}
So you can make your ball go both up and right or up and left by checking that both keys are pressed and then you can add to the velocity instead of the position to affect the trajectory of the ball. However, then you must slow down the x component of the velocity when it hits the ground, so I added a friction variable.
float px, py, vx, vy, ax, ay;
boolean canJump = false;
float bounce = 0.2;
float friction = 0.2;
void setup() {
size(600, 400);
ax = 0;
ay = .32;
vx = 0;
vy = 0;
px = 300;
py = 200;
}
int x = 50;
int y = 520;
void draw() {
background(0);
ellipse(px-15, py-30, 60, 60);
vx+=ax;
vy+=ay;
px+=vx;
py+=vy;
if ( py > height ) {
py = height;
vy = -bounce*vy;
vx = friction*vx;
canJump = true;
}
}
void keyPressed() {
if (keyCode == RIGHT && keyCode == UP) {
if (canJump) {
vy = -10;
vx += 5;
canJump = false;
}
} else if (keyCode == LEFT && keyCode == UP) {
if (canJump) {
vy = -10;
vx += -5;
canJump = false;
}
} else {
if (keyCode == RIGHT || key == 'd') {
vx += 5;
}
if (keyCode == LEFT || key == 'a') {
vx -= 5;
}
if (keyCode == UP) {
if (canJump) {
vy = -10;
canJump = false;
}
}
}
}
You can improve the implementation of your program by taking a look at processing's PVector class.
PVector pos;
PVector vel;
PVector acc;
float friction = 0.3;
float bounce = 0.5;
float diameter = 60;
boolean canJump = false;
void setup() {
size(600, 400);
pos = new PVector(300, 200);
vel = new PVector(0, 1);
acc = new PVector(0, 0.32);
}
void draw() {
background(0);
circle(pos.x, pos.y, diameter);
vel.add(acc);
pos.add(vel);
if (pos.y + diameter/2 > height) {
pos.set(pos.x, height-diameter/2);
vel.set(vel.x*friction, -vel.y*bounce);
canJump = true;
}
}
void keyPressed() {
boolean right = keyCode == RIGHT || key == 'd';
boolean left = keyCode == LEFT || key == 'a';
boolean up = keyCode == UP || key == 'w';
if (up && right && canJump) {
vel.add(5, -10);
canJump = false;
} else if (up && left && canJump) {
vel.add(-5, -10);
canJump = false;
} else {
if (up && canJump) {
vel.add(0, -10);
canJump = false;
}
if (right) {
vel.add(5, 0);
}
if (left) {
vel.add(-5, 0);
}
}
}

Processing/Java - Having trouble with Class Array

This is probably a really stupid question but I am having trouble showing more that one copy of my class on the screen.
I have created an asteroid class that generates and moves an asteroid on the screen. Yet when I try and call multiple versions of this class in my main body, it still only shows one asteroid.
Main
int lrgAsteroids = 4;
Asteroid[] asteroid = new Asteroid[lrgAsteroids];
void setup() {
size(800,800);
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i] = new Asteroid();
asteroid[i].display();
}
}
void draw() {
background(0);
asteroid[0].move();
asteroid[1].move();
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i].move();
}
}
asteroid class.
class Asteroid {
PImage lrgAsteroid;
float xpos, ypos;
float yDirection;
float xDirection;
float radians = 0;
Asteroid() {
lrgAsteroid = loadImage("largeAsteroid.png");
xpos = random(0,710);
ypos = random(0,710);
int xDir = (int) random(2);
int yDir = (int) random(2);
if (xDir == 1) {
xDirection = 1;
} else if (xDir == 0) {
xDirection = -1;
}
if (yDir == 1) {
yDirection = 1;
} else if (yDir == 0) {
yDirection = -1;
}
}
void display() {
image(lrgAsteroid, xpos, ypos);
}
void move() {
background(0);
pushMatrix();
imageMode(CENTER);
translate(xpos, ypos);
rotate(radians);
image(lrgAsteroid, 0, 0);
popMatrix();
if (xpos <= 0) {
xpos = random(750,800);
} else if (xpos >= 800) {
xpos = random(0,100);
}
if (ypos <= 0) {
ypos = random(750,800);
} else if (ypos >= 800) {
ypos = random(0,100);
}
radians += 0.02;
xpos += xDirection;
ypos += yDirection;
}
}
Any help would be greatly appreciated.
The bug is very simple. Actually the display is clear, before an asteroid is drawn, because of background(0); in the method move(). It is sufficient to clear the background at the begin of draw().
Remove background(0); from the method move():
Asteroid() {
// [...]
void move() {
// background(0); <---- DELETE
pushMatrix();
imageMode(CENTER);
translate(xpos, ypos);
rotate(radians);
image(lrgAsteroid, 0, 0);
popMatrix();
if (xpos <= 0) {
xpos = random(750,800);
} else if (xpos >= 800) {
xpos = random(0,100);
}
if (ypos <= 0) {
ypos = random(750,800);
} else if (ypos >= 800) {
ypos = random(0,100);
}
radians += 0.02;
xpos += xDirection;
ypos += yDirection;
}
}
I think that somehow all the instances that your create get the same xDir and yDir or same xpos and ypos , can you print it so you can see if that's the problem ?
void setup() {
size(800,800);
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i] = new Asteroid();
// add these please to see what happens
System.out.println(asteroid[i].xDirection+" "+asteroid[i].yDirection);
}
}
void draw() {
background(0);
asteroid[0].move();
asteroid[1].move();
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i].move();
// add these please to see what happens
System.out.println(asteroid[i].xpos+" "+asteroid[i].ypos);
}

Smooth movement in processing?

I want this code to effectively increase the smoothness of the transition between directions (it only works with one key at a time) so that I can use multiple keys. The problem is that whenever I change direction the "Player" stops and then continues in the new direction. I want the "Player" to smoothly transition between directions without having to fully release the active key before pressing the new one.
Main code:
Ball ball;
Player player1;
Player player2;
void setup() {
size(1368,768);
frameRate(60);
noStroke();
ball = new Ball(width/2, height/2, 30);
player1 = new Player(0, height/2, 30, 150);
player2 = new Player(width-30, height/2, 30, 150);
ball.speedX = -10;
ball.speedY = random(-5,5);
}
void draw() {
background(0);
ball.display();
ball.move();
player1.run();
player2.run();
//Collision
if (ball.top() < 0) {
ball.speedY = -ball.speedY;
}
if (ball.bottom() > height) {
ball.speedY = -ball.speedY;
}
if (ball.left() < 0) {
ball.speedX = 0;
ball.speedY = 0;
}
if (ball.right() > width) {
ball.speedX = 0;
ball.speedY = 0;
}
}
void keyPressed() {
player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.pressed((keyCode == UP), (keyCode == DOWN));
}
void keyReleased() {
player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.released((keyCode == UP), (keyCode == DOWN));
}
Player class code:
class Player {
float x, y;
int dy = 0;
float w, h;
float speedY = 5;
color c;
//Constructor
Player(float tempX, float tempY, float tempW, float tempH){
x = tempX;
y = tempY;
w = tempW;
h = tempH;
speedY = 0;
c = (255);
}
void run() {
display();
move();
}
void display() {
fill(c);
rect(x, y-h/2, w, h);
}
void move() {
y += dy * speedY;
}
void pressed(boolean up, boolean down) {
if (up) {dy = -1;}
if (down) {dy = 1;}
}
void released(boolean up, boolean down) {
if (up) {dy = 0;}
if (down) {dy = 0;}
}
}
Thanks in advance!
Add 2 attributes move_up and move_down to the class Player and set the attributes in
pressed respectively released:
class Player {
// [...]
boolean move_up = false, move_down = false;
void pressed(boolean up, boolean down) {
if (up) {move_up = true;}
if (down) {move_down = true;}
}
void released(boolean up, boolean down) {
if (up) {move_up = false;}
if (down) {move_down = false;}
}
}
Change speedY dependent on the attributes in move. Continuously reduce the speed if neither move_up not move_down is set (speedY = speedY * 0.95;). That causes that the player smoothly slows down if no key is pressed. If move_up or move_down is pressed the slightly change the speed dependent on the desired direction. Restrict the speed to a certain interval (speedY = max(-5.0, min(5.0, speedY));):
class Player {
// [...]
void move() {
if (!move_up && !move_down) {speedY *= 0.95;}
if (move_up) {speedY -= 0.1;}
if (move_down) {speedY += 0.1;}
speedY = max(-5.0, min(5.0, speedY));
y += speedY;
}
// [...]
}
Class Player:
class Player {
float x, y;
float w, h;
float speedY = 0.0;
color c;
boolean move_up = false, move_down = false;
//Constructor
Player(float tempX, float tempY, float tempW, float tempH){
x = tempX;
y = tempY;
w = tempW;
h = tempH;
c = (255);
}
void run() {
display();
move();
}
void display() {
fill(c);
rect(x, y-h/2, w, h);
println(y);
}
void move() {
if (!move_up && !move_down) {speedY *= 0.95;}
if (move_up) {speedY -= 0.1;}
if (move_down) {speedY += 0.1;}
speedY = max(-5.0, min(5.0, speedY));
y += speedY;
}
void pressed(boolean up, boolean down) {
if (up) {move_up = true;}
if (down) {move_down = true;}
}
void released(boolean up, boolean down) {
if (up) {move_up = false;}
if (down) {move_down = false;}
}
}
If you want smooth transitions, you're going to have to give up "adding a fixed integer distance" in the key handlers, and instead track which keys are down or not, and then accelerating/decelerating your player every time draw() runs. As simple illustration:
Box box;
boolean[] active = new boolean[256];
void setup() {
size(500,500);
box = new Box(width/2, height/2);
}
void draw() {
pushStyle();
background(0);
box.update(active); // First, make the box update its velocity,
box.draw(); // then, tell the box to draw itself.
popStyle();
}
void keyPressed() { active[keyCode] = true; }
void keyReleased() { active[keyCode] = false; }
With a simple box class:
class Box {
final float MAX_SPEED = 1, ACCELERATION = 0.1, DECELERATION = 0.5;
float x, y;
float dx=0, dy=0;
Box(float _x, float _y) { x=_x; y=_y; }
void draw() {
// We first update our position, based on current speed,
x += dx;
y += dy;
// and then we draw ourselves.
noStroke();
fill(255);
rect(x,y,30,30);
}
void update(boolean[] keys) {
if (keys[38]) { dy -= ACCELERATION ; }
else if (keys[40]) { dy += ACCELERATION ; }
else { dy *= DECELERATION; }
if (keys[37]) { dx -= ACCELERATION ; }
else if (keys[39]) { dx += ACCELERATION ; }
else { dx *= DECELERATION; }
dx = constrain(dx, -MAX_SPEED, MAX_SPEED);
dy = constrain(dy, -MAX_SPEED, MAX_SPEED);
}
}
The important part here is the update code, which updates the box's x and y velocity such that if a directional key is currently pressed, we increase the speeed (dx/dy) in that direction. Importantly, if no keys are pressed we also dampen the speed to that it returns to 0.
Finally, to make sure we don't end up with infinite speed, we cap the maximum allowed velocity.

Libgdx Accelerometer not working?

for some reason the block is not moving when I tilt the screen, and I don't know what's wrong. Just to clarify, I set the cfg.accelerometer to true, but the cfg.compass to false. Here's the source code-
public void update()
{
x += velX;
y += velY;
//movement
//left
if (Gdx.input.isKeyPressed(Keys.LEFT))
{
velX = -speed;
}
//right
if (Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = speed;
}
//up
if (Gdx.input.isKeyPressed(Keys.UP))
{
velY = -speed;
}
//down
if (Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = speed;
}
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
velX = Gdx.input.getAccelerometerX();
velY = Gdx.input.getAccelerometerY();
}
//stop
if (!Gdx.input.isKeyPressed(Keys.LEFT) && !Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = 0;
}
if (!Gdx.input.isKeyPressed(Keys.UP) && !Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = 0;
}
//collision with edges of screen
if (x <= 0)
{
x = 0;
}
if (x >= 1920 - width)
{
x = 1920 - width;
}
if (y <= 0)
{
y = 0;
}
if (y >= 1080 - height)
{
y = 1080 - height;
}
long recoveryElapsed = (System.nanoTime() - recoveryTimer)/1000000;
if (recoveryElapsed > 2000)
{
recovering = false;
recoveryTimer = 0;
}
System.out.println(lives+ " lives, recovering, "+recovering);
}
Help would be much appreciated, thanks. There are no tutorials that I have found with a working example shown, so I don't really know if what I am doing is correct, but I can't see anything wrong with it.
You are setting the Accel values, and then if the keys are not pressed you are setting them to 0 again. Do it like this:
//stop
if (!Gdx.input.isKeyPressed(Keys.LEFT) && !Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = 0;
}
if (!Gdx.input.isKeyPressed(Keys.UP) && !Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = 0;
}
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
velX = Gdx.input.getAccelerometerX();
velY = Gdx.input.getAccelerometerY();
}

How can i import variables to another class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make a prototype for a game i have to make for school. But it isnt going great. My question is how can i import a variable from one class to another? I want the playerX and Y variable so i can check collision. This is written in Processing (Java).
If there's a better way of checking collision please tell me :) im out of ideas. Thanks in advance!
My code:
Main class
Player thePlayer = new Player();
Guard theGuard = new Guard();
SpeedPWRUP speedPowerUp = new SpeedPWRUP();
void setup() {
size(1000, 500);
theGuard.init();
thePlayer.init();
speedPowerUp.init();
}
void updateGame() {
theGuard.update();
thePlayer.update();
speedPowerUp.update();
}
void drawGame() {
thePlayer.draw();
theGuard.draw();
speedPowerUp.draw();
fill(color(255, 255, 255));
text("Score:", 10, 20);
}
void draw() {
background(255);
fill (0, 0, 0);
rect(-10, 401, 1100, 100);
noFill();
updateGame();
drawGame();
}
Guard class
class Guard {
public float guardX, guardY;
float guardVX, guardVY;
int fillColor;
float guardHeight, guardWidth;
void init() {
guardHeight = 80;
guardWidth = 40;
guardX = 300;
guardY = 400-guardHeight;
fillColor = color(255,0,0);
}
void update() {
if (guardX == (random(width)-100))
guardVX = 3;
if (guardX == (random(width)+100))
guardVX = -3;
guardX += guardVX;
guardY += guardVY;
}
void draw() {
fill(fillColor);
rect(guardX, guardY, guardWidth, guardHeight);
noFill();
}
}
Player class
class Player {
public float playerX, playerY;
float vx, vy;
int fillColor;
float playerHeight, playerWidth;
float jumpTime;
float jumpHeight;
boolean isJumping;
void init() {
playerHeight = 80;
playerWidth = 40;
fillColor = color(0, 0, 0);
jumpTime = 200;
jumpHeight = 100;
isJumping = false;
playerX = 100;
playerY = 400-playerHeight;
vx = 0;
vy = 0;
}
void update() {
if (keyPressed) {
if (key == 'a' || key == 'A') {
vx = -2;
}
} else {
vx = 0;
}
if (keyPressed) {
if (key == 'd' || key == 'D') {
vx = 2;
}
} else {
vx = 0;
}
if (keyPressed) {
if ((key == 'w' || key == 'W') && ( playerY > 400 - jumpHeight)) {
isJumping = true;
}
} else {
isJumping = false;
}
if (playerY < 400 - jumpHeight) {
}
if (keyPressed) {
if (key == 's' || key == 'S') {
playerHeight = 40;
}
} else {
playerHeight = 80;
}
if(isJumping == true) {
vy = -15;
} else {
vy = 0;
}
if (playerY < (400-playerHeight)) {
vy = vy + 2.5;
}
playerX += vx;
playerY += vy;
}
void draw() {
fill(fillColor);
rect(playerX, playerY, playerWidth, playerHeight);
noFill();
}
}
Speed power up class
class SpeedPWRUP {
float diameter;
public float pwrUpX, pwrUpY;
int fillColor;
void init() {
diameter = 40;
pwrUpX = 100;
pwrUpY = 100;
fillColor = color(0, 0, 255);
}
void update() {
if (((playerX>pwrUpX) && (playerX < pwrUpX+diameter)) && (playerY > pwrUpY)&&(playerY>pwrUpY+diameter))
end();
}
void draw() {
fill(fillColor);
ellipse(pwrUpX, pwrUpY, diameter, diameter);
noFill();
}
}
To check collision:
You can define a static object in your main CLASS:
/* global static values */
public static Player thePlayer = new Player();
or list of players
public static ArrayList<Player> Players = new ArrayList<>();
You can use Getter functions in the Player class.
For instance:
public float getPlayerX(){
return playerX;
}

Categories

Resources