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

2013/1/30

Help with mouse control

SP00F3R SP00F3R

2013/1/30

#
I'm fairly new to Greenfoot and am using it to create a game for college. I'm creating a top down shooter styled game but I've encountered a small problem when trying to use the mouse to control where the character is facing. I have looked through some similar scenarios and attempted to adapt some of the code to work in my game but have found that the character and the mouse position aren't lined up. For example if my mouse is at the top of my world to make the character face that way it will be facing left, 90 degrees anti clockwise from where I want it to be. Apart from that small problem I've come across using this code, I was wondering if someone could roughly explain how the code works to help give me a better understanding of the math's and general principles involved. Many thanks.

private void setRotation()
     {
         if(Greenfoot.mouseMoved(null) || Greenfoot.mouseDragged(null)) {
             MouseInfo mouse = Greenfoot.getMouseInfo();
             mouseX = mouse.getX();
             mouseY = mouse.getY();
         }
         setRotation(pointTo(mouseX,mouseY));
    }

    public int pointTo(int x, int y)
    {
        int dX = x - getX();
        int dY = y  - getY();
        double rotation = Math.atan2(dY, dX); 
        rotation = Math.toDegrees(rotation); 
        return (int)rotation;
    }  

danpost danpost

2013/1/30

#
If your character is facing right before any turning of the object has occured, then the following should work:
if(mouseMoved(null))
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
    turnTowards(mouse.getX(), mouse.getY());
}
btw, it helps to know what methods are available to you.
SP00F3R SP00F3R

2013/1/30

#
Before I move the mouse, the character is facing up, its when I move the mouse in any direction the character is 90 degrees anti clockwise behind where the mouse is pointing if that makes sense? I don't fully understand what you mean regarding methods. The code I posted above, plus a few isKeyDown's, are all that are in my player class which is all I'm working on at the moment.
danpost danpost

2013/1/30

#
You will need to compensate for the fact that your character start by facing up instead of to the right (toward the right is zero degrees rotation). Either turn(90) after each time the rotation of the character changes or modify the image saved in the image file so it is facing right to begin with.
SP00F3R SP00F3R

2013/1/30

#
I rotated the image of the character and it works perfect, thanks a lot for the help.
You need to login to post a reply.