Moving Objects in Unity

Aus hyperdramatik
Zur Navigation springen Zur Suche springen

Unity : How to move a GameObject in 3D space?

There are different ways to move an object within 3D space with code. Here we go over 5 options:

A) transform.position

B) transform.Translate

C) RigidBody.AddForce

D) RigidBody.MovePosition

E) RigidBody.Velocity



B) transform.Translate

Similar to transform.position, but instead of assigning the GameObject a new position, it gives the GameObject an amount to move, data contained in a Vector3 struct.

  private void Update()
   {
       transform.Translate(Vector3.forward * Time.deltaTime);
   }


C) RigidBody.AddForce

RigidBody: Adding a Rigidbody component to a GameObject will put its motion under the control of Unity's physics engine, which is a long list of physical properties such as acceleration, mass, gravity, inertia, etc, as well as the capacity to react to other rigid bodies (for instance, collide).

RigidBody.AddForce: Adds a force vector to the class Rigidbody. Force can be applied only to an active Rigidbody. If a GameObject is inactive, AddForce has no effect. Specifying the ForceMode mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change.

public class RigidBodyAddForce : MonoBehaviour
{
   public float forceMult = 200; //velocity float multiplier
   private Rigidbody rb; //declarate Class Rigidbody

   private void Awake()
   {
       rb = GetComponent<Rigidbody>();
   }

   private void Update()
   {
       rb.AddForce(transform.up * forceMult * Time.deltaTime);
   }
}
  • The effect of the float forceMult (multiplier) over the RigidBody’s velocity is acceleration, it´s adding force every frame. A divider would be deceleration (transform.up / forceDiv).
  • GameObject is activated in private void Awake();
  • transform.up is the unit vector defined by (0, 0, 1).

D) RigidBody.MovePosition

Similar to transform.position but applied to a RigidBody, it sets the new position of the GameObject. Recommended to use with kinematic rigid bodies. When a RigidBody is marked as Kinematic, it will not be affected by collisions, forces, or any other part of Unity´s phisics engine.

public class RigidBodyMovePosition : MonoBehaviour
{ 
  public float forceMult = 100;
   private Rigidbody rb;

   private void Awake()
    
       {
           rb = GetComponent<Rigidbody>();
       }  
   private void Update()
   {
       rb.MovePosition(transform.position + (transform.forward * Time.deltaTime));
   }
}

E) RigidBody.Velocity

The velocity vector of the rigidbody. It represents the rate of change of the Rigidbody position.

public class RigidBodySetVelocity : MonoBehaviour
{
   public float forceMult = 200;
   private Rigidbody rb;

   private void Awake()
   {
       rb = GetComponent<Rigidbody>();
   }

   // Update is called once per frame
   private void Update()
   {
       rb.velocity = transform.forward * Time.deltaTime * forceMult;
   }