- Home /
Rigidbody.MovePosition not working correctly in unity 2017 and higher
void Update(){
float rotatey=Input.GetAxis("Mouse X");
transform.eulerAngles=new Vector3(0,transform.eulerAngles.y+rotatey*2,0);
x=Input.GetAxis("Vertical");
z=Input.GetAxis("Horizontal");
Vector3 moveVector=new Vector3(-x*3,0,z*3);
transform.GetComponent<Rigidbody>().MovePosition(transform.position+moveVector*Time.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?
Answer by mwnDK1402 · Feb 14, 2018 at 07:51 PM
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");
}
}
Your answer
Follow this Question
Related Questions
Rigidbody.MovePosition doesn't move reliably? 1 Answer
Move Rigidbody along curve 1 Answer
How do I stop unwanted rotations? 4 Answers
Rotation on rolling wheel 0 Answers