hi guys, i am doing a game where i have to detect whether my sprite collides with the wall horizontally or vertically, so in that case reverse the velocity of x or the velocity in y or both in some cases.
what i have done is that with an array of rectangles created the walls and with another rectangle around the sprite i am able to detect whether is colliding or not. but i dont know how to code whether is colliding horizontally or vertically so that i can change the velocities.
this is what i have :
the variable rectangle is the rectangle that surrounds the sprite.

public boolean rectcollision(){
	boolean collision = false;
	for (int i = 0; i < Game.m.rect.length; i++)
		Rectangle r=Game.m.rect[i];
		collision = true;
	return collision;

it loops through all the walls that are in the map and checks if the sprite collides with a wall.

i would really appreciate if someone can help me out. i am hoping i explained myself clear. thanks in advance

5 Years
Discussion Span
Last Post by elkowalski

If you used a small custom class for your wall, you could have an axis property for horizontal or vertical. On collision you can check the wall axis to know which velocity to change.

You can still keep a Rectangle inside the class to manage the bounds and forward your intersect calls to that rectangle.


i have a class that reads a txt file with 0s and 1s and creates a whole map, draws the images and creates rectangles for every single 1 in the map. what do you mean with creating and axis property?


I was thinking you might know when you placed it whether a wall lay along the X axis or Y axis, in which case you could keep track of that when you built them. Axis could be an int or enum property on a Wall class.

If you're building them block by block, the outcode() method on Rectangle2D might be more helpful in determining where your sprite is located in relation to the rectangle.


oh okay i see i will have to look into the outcode(). yes every block can collide vertically or horizontally so there is no way i can say that it has the property of only horizontal or vertical because it needs towork with both

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.