Attention |
Topic was automatically imported from the old Question2Answer platform. | |

Asked By |
Yaann |

Hello guys, I’m trying to make a 2.5D top-down shooter using a mix of 2D and 3D assets and I would like to make my character turn toward the mouse’s position while the camera is following him.

I’m using a position3D to turn my character around, what I want is that the postion3D always faces the mouse.

I managed to get the mouse’s position using GetViewpoint().GetMouseposition(), the problem now is how to make the position3D’s rotation rotate towards it.

This is just a matter of fiddling with math!

You have to get two values first: the player position and the mouse position.

If your mouse position is relative to the viewport, you’ll have to get the player position relative to the viewport as well. If the mouse position is relative to the world, you’ll have to get the player position relative to the world as well.

Calculate the x- and y-difference between the two points (which can be done using a vector). Now you have the vector from the player towards the point the mouse is at.

Now all you have to do is calculate the angle between the horizontal vector and the vector you just calculated, and update the rotation of your player according to that angle. Do this every tick in the _process() function, and you will have the result you want.

To show you how to calculate the angle, I will use vector math, and in particular a concept called the *dot-product*. You can read more about it here: How do I calculate the angle between two vectors? | Socratic

Alright, on to the code!

You might have to fill in some additional stuff, such as the method how you get the mouse position or the player position, but this is how the math should work:

```
func _process(delta):
# Get all values.
var mouse_pos = Vector2(x, y)
var player_pos = Vector3(x, y, z)
var delta_x = mouse_pos.x - player_pos.x
var delta_y = mouse_pos.y - player_pos.y
# Calculate angle here:
var dot_product = delta_x * HOR_VECTOR.x + delta_y * HOR_VECTOR.y
var mag_touch_vector = sqrt(delta_x * delta_x + delta_y * delta_y)
# The 1 in below calculation is the magnitude of the horizontal vector,
# which is always 1. You can leave it out if you want.
angle = (dot_product / (mag_touch_vector * 1))
# Now update the player rotation:
self.rotation_degrees.y = angle
```

If something isn’t working, don’t hesitate to ask about it!

~FortunePilot

FortunePilot | 2020-04-20 15:03

I was fiddling with math too, guess my theories didn’t work lol.

Anyway, I found another way to fix my problem but I’ll keep your method around in case of mine screws up in the long run, thanks for the help!

Yaann | 2020-04-20 20:12