开发者

Collision system for an object?

开发者 https://www.devze.com 2023-02-28 19:47 出处:网络
I am making a small game, 2D, and I have a player. EDIT: This is what I have right now:开发者_开发技巧

I am making a small game, 2D, and I have a player.

EDIT:

This is what I have right now:开发者_开发技巧

        int oldX = player.x;
    int oldY = player.y;

    int newX = oldX - player.getSpeedX();
    int newY = oldY - player.getSpeedY();

    if(player.getBounds().intersects(brush1.getBounds())){
        player.x = newX;
        player.y = newY;
    }else{
        player.x = oldX;
        player.y = oldY;
    }

But, it is acting really weird, it changes speed when I go in from one side, etc.


For a formula and code that checks the intersection of a line segment and a circle, have a look at this SO answer.

The rest of the code should be quite clear, before you make a move, check if a collision occurs, if it would, don't move.

Depending on the behaviour you prefer, you could also move as close to the wall as possible and then move parallel to it to let the circle "slide" along the wall. This can be done by projecting the movement vector on a line with the same direction as the wall.

EDIT: Some comments on how to use the code from the answer to check for collisions:

The code uses a Dot function that computes the dot product of two vectors. You can either create a Vector class (a good exercise and it is useful for such projects) or compute just the dot product directly using the formulas here.

A vector class will make some of the code easier to read, but you can also operate on floats directly. For example, let's have a look at the computation of d (Direction vector of ray) and f (Vector from center sphere to ray start) as described at the start of the answer. With a vector class, this will be as easy as the formulas used there:

// L, E, C, d and f are of some vector type
d = L - E;
f = E - C;

Without a vector class, you'll have seperate x/y coordinates for all of the variables, bloating the code a bit but doing just the same:

// Twice as much variables, but all of them are usual floats.
dx = Lx - Ex;
dy = Ly - Ey;
fx = Ex - Cx;
fy = Ey - Cy;


I think your code snippet has a few bugs. Suggested fixes:

int oldX = player.x;
int oldY = player.y;

// *add* speed to old pos to get new pos
int newX = oldX + player.getSpeedX();
int newY = oldY + player.getSpeedY();

if(player.getBounds().intersects(brush1.getBounds())){
    // Collision!  Keep old position.
    // Reverse speed (just a suggestion).
    player.setSpeedX(-player.getSpeedX());
    player.setSpeedY(-player.getSpeedY());
}else{
    // No collision.  Set position to *new* pos, not old pos.
    player.x = newX;
    player.y = newY;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消