Home > Enterprise >  Changing direction in 3D
Changing direction in 3D

Time:01-30

I am working on a 3D project, in Unity.

I have an object moving in a confined space. The object have a fixed velocity, and it bounces back once they reach the space limit.

I want it to change direction once every n seconds.

The problem I am facing is: How to rotate a 3D vector by a given angle.

In 2D is pretty easy, while in 3D I am not sure how to handle it.

Can someone help me with that?

CodePudding user response:

In 2D this is simple...

In three 3 as well.

You can e.g. simply rotate a Vector3 about any given Euler angles via

var newVector = Quaternion.Euler(x, y, z) * oldVector;

question remains where you get those angles from and whether those are random or you are rather looking for Reflect the vector once the objects reach your defined area constraints.

You can as well simply invert the individual components like e.g.

// Note for simplicity reasons this is not an actual "distance"
// but rather the maximum of each individual axis
public float maxDistance;

private Rigidbody _rigidbody;

private void Start ()
{
    _rigidbody = GetComponent<Rigidbody>();
    _rigidbody.velocity = Random.insideUnitSphere.normalized;
}

private void FixedUpdate()
{
    var vel = _rigidbody.velocity;
    var pos = _rigidbody.position;

    if(Mathf.Abs(pos.x) >= maxDistance)
    {
        vel.x *= -1;
    }

    if(Mathf.Abs(pos.y) >= maxDistance)
    {
        vel.y *= -1;
    }

    if(Mathf.Abs(pos.z) >= maxDistance)
    {
        vel.z *= -1;
    }

    _rigidbody.velocity = vel;
}

CodePudding user response:

You can change directions by a certain angle on a certain axis, making it similar to 2D.

If you are moving the object with its transform you can easily rotate an object with the Rotate method on the game object transform.

//in a script attached to the game object you want to rotate
transform.Rotate(Vector3.up, Random.Range(90,270), Space.self);

You can now use transform.forward to move the object.

If you want to go deeper into 3D rotation have a look at Quaternions

You can use the Quaternion.operator * to rotate one rotation by another, or to rotate a vector by a rotation.

Consider also looking at the Vector3 class methods such as Reflect and RotateTowards.

Tip: To keep a consistent speed across all directions, consider normalizing the direction vector, (0,1,1) will travel faster than (0,0,1).

You can normalize any vector as follows:

Vector3 direction = Vector3.up   Vector3.forward; //(0,1,1)
direction = direction.normalized; //(0,0.71,0.71)
  • Related