- Home /
player rotation to follow the mouse
If anyones played the game alien swarm, I want the player to rotate 360 degrees based on mouse movement for aiming like it does in that game. In other words, a full circular motion around the player will cause the player to rotate 360 degrees. My game is a top down view also like alien swarm....check the game out on yt to see what i mean.
How can I do the mouse based rotation in unity? I've tried so many things but nothing works so far.
The couple of video I saw, were 3D with an angled down view. Is this the situation you are trying to use?
Answer by robertbu · Oct 01, 2014 at 03:40 AM
Assuming you constructed your player facing positive 'z' when the rotation is (0,0,0) then something like this should do the job:
using UnityEngine;
public class Example : MonoBehaviour {
void Update() {
Plane plane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float dist;
if (plane.Raycast (ray, out dist)) {
transform.LookAt (ray.GetPoint(dist));
}
}
}
Answer by sevensixtytwo · Oct 01, 2014 at 03:45 AM
Here's a short breakdown of a mouse-aim system.
Find out where the mouse is in world space.
Get your target point from the mouse position.
Rotate the player's aim towards the target point.
I suggest reading up on Camera.ScreenPointToRay, Input.mousePosition, Physics.Raycast and Quaternion.RotateTowards.
Not that this is the only way to do it. Methods vary but only results matter.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164134im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Quaternions acting up 1 Answer
Why is this rotation acting odd? 0 Answers
Connecting transform with Vector3 4 Answers
Rotating an Object to its Original Angles after certain distance from ground 1 Answer