This site requires JavaScript, please enable it in your browser!
Greenfoot back
xsolvite
xsolvite wrote ...

2021/2/23

How do you bounce a bullet off of a wall in the opposite direction?

xsolvite xsolvite

2021/2/23

#
I'm making a tank shooting game, and I want the bullets to bounce off the walls like they do in Breakout I currently have
public void bounce()
    {
        Actor wall = getOneIntersectingObject(Wall.class);
        if (wall != null)
        {
            setRotation(getRotation() * -1);
        }
    }
However, this only works for the top and bottom of the walls, not the right and left. Does anyone know how to fix that?
danpost danpost

2021/2/24

#
xsolvite wrote...
I'm making a tank shooting game, and I want the bullets to bounce off the walls like they do in Breakout I currently have << Code Omitted >> However, this only works for the top and bottom of the walls, not the right and left. Does anyone know how to fix that?
Please provide movement code and act method, as well.
xsolvite xsolvite

2021/2/25

#
I've done this and it seems like it works. but they only problem is that sometimes the bullets get stuck in the walls (but that's probably a hitbox error)
public class Bullet extends Actor
{
    /**
     * Act - do whatever the Bullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        bounce();
        move(4);
    }    
    
    public void bounce()
    {
        int rotateVertical = 0;
        int rotateHorizontal = 0;
        Actor horizontalWall = getOneIntersectingObject(HorizontalWall.class);
        Actor verticalWall = getOneIntersectingObject(VerticalWall.class);
        
        //bounce on horizontal walls
        if (horizontalWall != null)
        rotateHorizontal = 1;
        if (getY() <= 0 || getY() >= 499)
        rotateHorizontal = 1;
        if (rotateHorizontal == 1)
        {
            setRotation(getRotation() * -1);
            rotateHorizontal = 0;
        }
        
        //bounce on vertical walls
        if (verticalWall != null)
        rotateVertical = 1;
        if (getX() <= 0 || getX() >= 498)
        rotateVertical = 1;
        if (rotateVertical == 1)
        {
            setRotation((getRotation() - 180) * -1);
            rotateVertical = 0;
        }
    }
}
danpost danpost

2021/2/25

#
Collision checking should come AFTER any change in position (or rotation) -- that is, any change not dictated by collision to begin with. There are two actions that should be performed when a collision occurs: moving (or rotating) off the object collided with and turning. The first of these is often missed by young coders.
You need to login to post a reply.