Remixt
Remixt

Reputation: 597

Why won't my rigid body stop moving on collision?

I'm new to Unity.

Below is my simple character controller C# script. I'm using 3d cubes with box colliders and rigid bodies as both my walls and player. Currently when my player comes into contact with a wall, it just keeps going.

Why is my script not working?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controller : MonoBehaviour {

    public float speed = 180;

    private Rigidbody rig;

    private Vector3 movement;
    // Use this for initialization
    void Start () {

        rig = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate () {

        if (rig.velocity.magnitude <= 0)
        {
            if (Input.GetKeyUp("up"))
                rig.velocity = new Vector3(0, 0, rig.position.z * speed );            
            else if (Input.GetKeyUp("down"))
                rig.velocity = new Vector3(0, 0, rig.position.z * speed * -1);
            else if (Input.GetKeyUp("right"))
                rig.velocity = new Vector3(rig.position.x * speed, 0, 0);
            else if (Input.GetKeyUp("left"))
                rig.velocity = new Vector3(rig.position.x * speed * -1, 0, 0);
        }
    }

    void OnCollisionEnter(Collision collision)
    {
            rig.velocity = Vector3.zero;
    }
}

Upvotes: 1

Views: 374

Answers (1)

Remixt
Remixt

Reputation: 597

The script above works... My y position was higher than the position of my walls so there was never any collision. I feel dumb. Leaving post up as a reminder of my failure.

Upvotes: 4

Related Questions