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

2016/4/7

Making bullets fire in different directions

GodlikeStorm GodlikeStorm

2016/4/7

#
This code is in the player class called "SnowMan"
public void timer()
    {
        if (shotTimer > 0)
        {
		shotTimer--;
        }
        else if (Greenfoot.isKeyDown("enter"))
        {
            getWorld().addObject(new TowerShot(this),getX(),getY());
            {
                shotTimer = 200;
            }
        }
    }
This code is in the TowerShot class
public class TowerShot extends Actor
{
    /**
     * Act - do whatever the TowerShot wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
    
    
    int ypos = getY();
    ypos = ypos -5;
    setLocation(getX(),ypos);
    if (isAtEdge())
    {
        getWorld().removeObject(this);
    }
} 
    private SnowMan myTurret;
    public TowerShot(SnowMan myTurret)
    {
        this.myTurret = myTurret;
    }
       
}
I want to make it so that the TowerShot will fire in the direction the player is facing and not in the same direction (up) all the time! Any help or advice would be greatly appreciated!
Super_Hippo Super_Hippo

2016/4/7

#
Why do you pass the SnowMan to the TowerShot? So in other words, why does the bullet need to know who shoot it? With the code how it is right now, you can add the following line after line 22 in the TowerShot class:
setRotation(myTurret.getRotation);
Since the SnowMan itself isn't needed and only his rotation is, you don't have to pass the SnowMan - you can remove the constructor and the 'myTurret' variable - and just adjust the rotation when adding the object:
Actor bullet = new TowerShot();
getWorld().addObject(bullet, getX(), getY());
bullet.setRotation(getRotation());
GodlikeStorm GodlikeStorm

2016/4/8

#
Greenfoot cannot find a variable called getRotation so i cant put that first line of code in, any ideas?
Super_Hippo Super_Hippo

2016/4/8

#
Sorry, it's this:
setRotation(myTurret.getRotation());
It's not a variable, it's a method. The '()' was missing.
You need to login to post a reply.