# GMS 2 How to move relative to the mouse

Discussion in 'Programming' started by gamer_essence, Mar 1, 2018.

1. ### gamer_essenceMember

Joined:
Dec 2, 2016
Posts:
44
So i have a character that moves but i want to move him in correspondance with the mouse. I.e. if you press w it moves toward the mouse and s it goes backwards. I also want to have it move left and right in correspondance with the mouse as well. I've tried for hours to figure this out and anything i do doesnt work so any help would be appreciated.

2. Just get the angle to the mouse and then use trig
Code:
```angle = point_direction(x, y, mouse_x, mouse_y);
max_speed = 5;

if(keyboard_check(ord("W"))){
x += max_speed * dcos(angle);
y += max_speed * dsin(angle);
}
if(keyboard_check(ord("S"))){
x -= max_speed * dcos(angle);
y -= max_speed * dsin(angle);
}
```

3. ### JFitchMember

Joined:
Sep 28, 2016
Posts:
428
Since Game Maker uses up as -y and down as +y, it may actually be this:
Code:
```angle = point_direction(x, y, mouse_x, mouse_y);
max_speed = 5;

if(keyboard_check(ord("W"))){
x += max_speed * dcos(angle);
y -= max_speed * dsin(angle);
}
if(keyboard_check(ord("S"))){
x -= max_speed * dcos(angle);
y += max_speed * dsin(angle);
}
```

4. ### gamer_essenceMember

Joined:
Dec 2, 2016
Posts:
44
well this solves the forward and backward problem but what about left and right? It might be simple but i can not figure out how. The only way that i can think of is making it move 90 degrees from that direction but i dont know how

5. ### JFitchMember

Joined:
Sep 28, 2016
Posts:
428
Code:
```angle = point_direction(x, y, mouse_x, mouse_y);
max_speed = 5;

if(keyboard_check(ord("W"))){
x += max_speed * dcos(angle);
y -= max_speed * dsin(angle);
}
if(keyboard_check(ord("S"))){
x -= max_speed * dcos(angle);
y += max_speed * dsin(angle);
}
if(keyboard_check(ord("A"))){
x -= max_speed * dsin(angle);
y -= max_speed * dcos(angle);
}
if(keyboard_check(ord("D"))){
x += max_speed * dsin(angle);
y += max_speed * dcos(angle);
}```

Guest User likes this.