Home > Enterprise >  Freezing Movement to the side after rotating GameObject
Freezing Movement to the side after rotating GameObject

Time:01-19

I am trying to freeze the position of a GameObject towards the z-Axis but when turning the GameObject the z-Axis should turn with it (or atleast the freeze Position)

So basically I want my object to only be able to move forward, backwards and up and down, no matter what direction it is facing.

A RigidBody freeze Position is in relation to the world axis and not the rotated axis of the object.

Appreciate the help, thank you

Top Down View of Object, before rotation and after

CodePudding user response:

You can get the GameObject's "z-axis" with transform.forward. If this isn't the axis you want, try transform.right or transform.up.

It's unclear what you're asking for. Here are two cases that might answer your question:

To confine velocity to the "z-axis":

//reference to the Rigidbody to restrict
private Rigidbody rig;
void Start(){
    //find the Rigidbody attached to this GameObject
    rig = GetComponent<Rigidbody>();
}

//Updates every physics frame
void FixedUpdate(){
    //set the velocity to the component of the velocity that is parallel to the forward direction
    rig.velocity = transform.forward * Vector3.Dot(transform.forward, rig.velocity);
}

If you don't want any movement in the "z-axis", replace the rig.velocity = ... line with rig.velocity -= ...

Put this code in a MonoBehaviour (script) attached to your GameObject.

Note that if the GameObject is physically hit, it might spin, causing the "z-axis" to rapidly change. To prevent this, you could use the Rigidbody freeze rotation.

  •  Tags:  
  • Related