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

2020/9/25

Is there an alternative to setLocation that uses the type double?

byNici byNici

2020/9/25

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
public class Player extends Actor
{
    int speed = 5;
    int moveX;
    int moveY;
     
    public void act()
    {
        Input();
        if(moveX != 0 && moveY != 0)
        {
            setLocation(getX() + moveX * speed * Math.sqrt(2), getY() + moveY * speed * Math.sqrt(2));
        }
        else
        {
            setLocation(getX() + moveX * speed, getY() + moveY * speed);
        }
    }   
     
    public void Input()
    {
        moveX = 0;
        moveY = 0;
        if(Greenfoot.isKeyDown("a"))
        {
            moveX = -1;
        }
        else if(Greenfoot.isKeyDown("d"))
        {
            moveX = 1;
        }
        if(Greenfoot.isKeyDown("w"))
        {
            moveY = -1;
        }
        else if(Greenfoot.isKeyDown("s"))
        {
            moveY = 1;
        }
    }
}
So i'm trying to normalize the vertical movement and figuerd that I just have to multiple the vector by the squareroot of 2 but Math.sqrt(2) gives back a double and that does'nt match with setLocation because it needs an integer. Any help?
danpost danpost

2020/9/25

#
byNici wrote...
Is there an alternative to setLocation that uses the type double?
There is not -- at least, not among the methods given in the greenfoot package. However, that does not preclude you from making one yourself; or from importing a class that does have one. The SmoothMover class has a setLocation(double, double) method. Use the menu bar commands "Edit >> Import class ..." and select it. Then have your Actor subclass extend it. You will then have to modify your code to make use of it.
You need to login to post a reply.