Home > front end >  Use MoveRotation to Look At Another Object Unity3d
Use MoveRotation to Look At Another Object Unity3d

Time:01-09

Basically I am looking for a simple way for using the rigidbody/physics engine to have my ship look at another object (the enemy). I figured getting the direction between my transform and the enemy transform, converting that to a rotation, and then using the built in MoveRotation might work but it is causing this weird effect where it just kind of tilts the ship. I posted the bit of code as well as images of before and after the attempt to rotate the ship (The sphere is the enemy).

private void FixedUpdate()
 {
     //There is a user on the ship's control panel.
     if (user != null)
     {
         var direction = (enemyOfFocus.transform.position - ship.transform.position);
         var rotation = Quaternion.Euler(direction);
         ship.GetComponent<Rigidbody>().MoveRotation(rotation);
     }
 }

Before.
enter image description here
After.
enter image description here

CodePudding user response:

Well the Quaternion.Euler is a rotation about the given angles, for convenience provided as a Vector3.

Your direction is rather a vector pointing from ship towards enemyOfFocus and has a magnitude so the x, y, z values also depend on the distance between your objects. These are no Euler angles!

What you rather want is Quaternion.LookRotation (the example in the docs is basically exactly your use case ;) )

var direction = enemyOfFocus.transform.position - ship.transform.position;
var rotation = Quaternion.LookRotation(direction);
ship.GetComponent<Rigidbody>().MoveRotation(rotation);
  •  Tags:  
  • Related