Stop movement or rotation of a Unity GameObject with C#

Hello programmers, in this article, I will show how to stop the movement or rotation of a Unity GameObject with C#.

A game object must move and must be stopped according to certain circumstances in order for it to function properly. This is an important component in making any game.

Rigidbody.Velocity

The rigidbody’s velocity vector. It stands for the rigidbody position’s rate of change.

Most of the time, you should avoid changing the velocity directly because doing so might produce unnatural behavior.

Setting an object’s velocity at every physics step will result in an unrealistic physics simulation.

In a first-person shooter, changing the velocity is frequently used when leaping since you want the velocity to alter right away.

Vecto3.zero

Public static Vector3 zero;

Vector3.zero is the short form for the Vector3(0, 0, 0)

Syntax :

transform.position = Vector3.zero;

C# Script

Below is our C# program that can stop the movement or rotation of a Unity GameObject:

using UnityEngine;
using System.Collections;

public class CharacterController : MonoBehaviour
{
    Rigidbody rb;

    // Start is called before the first frame update 
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = vector3.zero;
        }
    }
}

If the user presses the Space Key it will stop the movement and rotation of the game object.

Leave a Reply

Your email address will not be published. Required fields are marked *