- Home /
I want to make the mouse rotate an object. How do I make this code work
What do i put inside the brackets? This is the code:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float rspeed = 20;
private Rigidbody rig;
// Use this for initialization
void Start ()
{
rig = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update ()
{
float mouse = Input.GetAxis("Mouse Y");
Vector3 rotation = new Vector3(0, mouse, 0) * rspeed * Time.deltaTime;
rig.MoveRotation(??????);
}
}
Answer by b1gry4n · Oct 13, 2016 at 12:38 PM
put "Quaternion.Euler(rotation)" inside the bracket, however, if you are not storing the value of your current rotation, the object will reset to a 0,0,0 rotation. the reason being, moving the mouse in one direction will give 1, moving it in the opposite will give -1, and not moving it at all will give 0. plugging in 0 as the y vector3 in your "rotation" vector, will essentially make it Vector3.zero. Multiplying anything by 0 will return 0. By storing the rotation in the current frame, even if mouse input is 0, the desired rotation will be the current rotation
public float rspeed = 20;
public float smoothness = 5;
private Rigidbody rig;
// Use this for initialization
void Start()
{
rig = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//get the current mouse input. Will be 1, 0, or -1
float mouse = Input.GetAxis("Mouse Y");
//the desired rotation, affecting the Y value only, will be the current value of the rotation in this frame + ("mouse" (1,0,-1) * speed)
Vector3 desiredRot = new Vector3(0, rig.rotation.eulerAngles.y + (mouse * rspeed), 0);
//Slerp the current rotation to the desired rotation over delta time.
//Higher smoothness will make it snap to the desired rotation fast, lower values will make it rotate slower
rig.rotation = Quaternion.Slerp(rig.rotation, Quaternion.Euler(desiredRot), Time.deltaTime * smoothness);
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Multiple Cars not working 1 Answer
How to rotate an object to a specific angle with angularVelocity? 0 Answers
Distribute terrain in zones 3 Answers
Bullet not moving towards player 3 Answers