void Update(){
float rotatey=Input.GetAxis(“Mouse X”);
transform.eulerAngles=new Vector3(0,transform.eulerAngles.y+rotatey2,0);
x=Input.GetAxis(“Vertical”);
z=Input.GetAxis(“Horizontal”);
Vector3 moveVector=new Vector3(-x3,0,z3);
transform.GetComponent().MovePosition(transform.position+moveVectorTime.deltaTime);
}
The script above is working perfectly in unity 5.6.1f (it allows cube to move with wsad and rotate on y axis with mouse at the same time)
However on unity 2017 and 2018 the same script is working differently. The cube moves only when it’s not rotating,so if i touch my mouse to change the rotation of the object it’s stop moving.It’s important for my project to allow objects to rotate and move at the same time,so how can i change the code to make it work on the newer versions of unity?
The problem lies in the fact that you’re changing the rotation of the Transform while changing the position of the Rigidbody. I won’t go into too much detail, so I’ve included some code which solves the problem while also avoiding redundant calls in Update.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
internal sealed class Movement : MonoBehaviour
{
private Vector2 input;
[SerializeField]
private float movementMultiplier = 1f, rotationMultiplier = 1f;
private Rigidbody rb;
private float rotation;
private void Awake()
{
this.rb = this.GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
var rotation = Quaternion.Euler(
0,
this.rb.rotation.eulerAngles.y + (this.rotation * this.rotationMultiplier),
0);
this.rb.MoveRotation(rotation);
var movement = new Vector3(
-this.input.y * this.movementMultiplier,
0,
this.input.x * this.movementMultiplier);
this.rb.MovePosition(this.rb.position + movement * Time.deltaTime);
}
private void Reset()
{
this.GetComponent<Rigidbody>().useGravity = false;
}
private void Update()
{
this.input.x = Input.GetAxis("Horizontal");
this.input.y = Input.GetAxis("Vertical");
this.rotation = Input.GetAxis("Mouse X");
}
}