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

2012/12/4

Move in the direction of a mouse click?

solokeh solokeh

2012/12/4

#
I recently started coding in Greenfoot and I am making a simple top down shooter, I was wondering how to make an actor (In this case, a bullet) move in the direction of a mouse click. I would greatly appreciate any help I receive.
danpost danpost

2012/12/4

#
You could create the bullet and add it to the world, placing it at the location that the mouse was clicked; then, turn the actor (gun or player) toward the bullet (using 'turnTowards'); then reset the location of the bullet to that of the actor and rotate the bullet to the rotation of the actor. Depending on the actor, you may want to reset that actor's rotation to that which it was before 'firing' the bullet; but, being a top-down, you probably want to leave it there.
legoman legoman

2012/12/4

#
Why not start the bullet at your gun/player to begin with? There's no need to start it at where it was clicked. Realize that although turnTowards is a great simple method, using it with move alone will only move your bullet at 45 degree angles. It's a little more work to get around this, ask if you want to get into detail.
danpost danpost

2012/12/4

#
@legoman, without having the bullet (or some object) at the point of the mouse click, you would have to calculate the angle to turn towards yourself. Also, you are only restricted to 45 degree angles when the move is a one-pixel move -- 'move(1)'. A normal bullet would have a much higher rate of speed which opens up a multitude of directions.
solokeh solokeh

2012/12/4

#
Thanks for the help, but I just did this: private void shoot() { if(Greenfoot.mouseClicked(null)) { Actor bullet = new Bullet(); MouseInfo mouse = Greenfoot.getMouseInfo(); getWorld().addObject(bullet, getX(), getY()); bullet.turnTowards(mouse.getX(), mouse.getY()); }
danpost danpost

2012/12/4

#
I must've been having synoptic mis-firings this morning. Of course all you need is the location to 'turnTowards'!
Hawx_ Hawx_

2013/1/9

#
I'm getting an error on this line of code
Ball.turnTowards(mouse.getX(), mouse.getY());
"Cannot find method turnTowards." Am I meant to define the method ? Help, Thanks, Hawx
danpost danpost

2013/1/9

#
@Hawx_, the 'turnTowards' method is in the Actor API and needs an Actor object to run on. If this line of code is in the Ball class 'act' method (or a method that the 'act' method calls), just use:
turnTowards(mouse.getX(), mouse.getY());
// which is equivalent to
this.turnTowards(mouse.getX(), mouse.getY());
You need to login to post a reply.