Search Unity

Discussion collision not working properly in unity when moving

Discussion in 'Scripting' started by imranhasmi5434, Oct 19, 2022.

  1. imranhasmi5434

    imranhasmi5434

    Joined:
    Oct 19, 2022
    Posts:
    1
    so I have rigid body and when it collides with another body with low speeds it is working just fine but when it collides with hight speed it goes through the object I've Been have this problem for day and I can't fix it

    here's my code

    this is my player movement file site....

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CharcterController : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.     public Vector3 PlayerMovementVar;
    9.  
    10.     public Rigidbody Rigidbody_comp;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         Rigidbody_comp = GetComponent<Rigidbody>();
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         PlayerMovement();
    21.      
    22.     }
    23.  
    24.     void PlayerMovement()
    25.     {
    26.         float horizontalAxis = Input.GetAxis("Horizontal")/30;
    27.         float verticalAxis = Input.GetAxis("Vertical")/30;
    28.         PlayerMovementVar = new Vector3(horizontalAxis,0f,verticalAxis);
    29.         transform.Translate(PlayerMovementVar,Space.Self);
    30.     }
    31. }
     
    Last edited: Oct 26, 2022
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,491
    This doesn't look like anything useful at all. You're not supposed to write to the Transform, that's the job of the Rigidbody. You're supposed to use the Rigidbody API to cause movement. You've got a Rigidbody here but don't do anything with it. You're just changing the Transform which will cause the Rigidbody (when the simulation runs next) to instantly be at the new position i.e. teleport to that location causing overlaps or even tunnelling over other colliders etc.

    I would suggest looking at some basic physics tutorials and, sorry to say, throw the code above away.
     
  3. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    657
    As Melv said, you have a rigidbody, that you even cached, but then you don't use it. This is why the physics is not functioning correctly.

    Look up Rigidbody.MovePosition, Rigidbody.AddForce, rigidigbody.velocity . all of this can be found with example in the scripting api documentation, and in fact is amongst the most common type of tutorials one can find. GL