Rotate a GameObject smoothly towards mouse
Hi.
I'm very new to Unity, but I do have some programming experience. Mostly things like Powershell and Python to automate my job, so I'm not very familiar with graphical programming and physics.
I'm having some trouble rotating a GameObject towards my mouse. I know what I have to use Quaternion.Slerp to move it smoothly, but I can't for the life of me figure this out! I have managed to sort of make it rotate, but it's all wrong. I expect it's something to do with my rotateTo Quaternion, but I'm not sure.
Any help would be greatly appreciated!
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
private Vector3 mousePosition;
public float moveSpeed = 2f;
public float lookSpeed = 5f;
void Start () {
}
void Update () {
if (Input.GetMouseButton(1)) {
MoveCharacter ();
RotateCharacter ();
}
}
void MoveCharacter() {
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = Vector2.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
Debug.DrawLine (transform.position, mousePosition, Color.red);
}
void RotateCharacter() {
float angle = Mathf.Atan2(Input.mousePosition.x, Input.mousePosition.y) * Mathf.Rad2Deg;
Quaternion rotateTo = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotateTo, Time.deltaTime * lookSpeed);
}
}
If you run the script, you'll see a debug line in the scene editor. The line points to where I want to rotate my GameObject.
Answer by Fjonan · Jan 09, 2018 at 04:14 PM
Maybe you can use this script by @SebastianLague you can also find on github. He explains it very nicely in this tutorial here.
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
public float moveSpeed = 6;
Rigidbody rigidbody;
Camera viewCamera;
Vector3 velocity;
void Start () {
rigidbody = GetComponent<Rigidbody> ();
viewCamera = Camera.main;
}
void Update () {
Vector3 mousePos = viewCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, viewCamera.transform.position.y));
transform.LookAt (mousePos + Vector3.up * transform.position.y);
velocity = new Vector3 (Input.GetAxisRaw ("Horizontal"), 0, Input.GetAxisRaw ("Vertical")).normalized * moveSpeed;
}
void FixedUpdate() {
rigidbody.MovePosition (rigidbody.position + velocity * Time.fixedDeltaTime);
}
}
Your answer
Follow this Question
Related Questions
Can't really grasp how to keep my player level on X and Z while using LookRotation 0 Answers
[Solved] Smooth rotation with keydown 2 Answers
How to use Quaternion.Slerp with transform.LookAt? 3 Answers
unwanted rotation in y axis 0 Answers
Rotation problem 0 Answers