Home > other >  RigidBody passes through objects in Unity
RigidBody passes through objects in Unity

Time:06-11

I am creating an FPS in unity and am using a capsule collider with a RigidBody. When the player is being squeezed by two other objects in a small space and allows the player to fly, clip through objects, and other unintended stuff that I don't want. Here is the player controller script:

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

    public class fpsController : MonoBehaviour
    {
        public InputMaster inputMaster;
        private Rigidbody rig;
        public Vector2 inputVector;
        public Transform groundcheck;
        public bool isGrounded;
        float speed = 6f;
        public LayerMask whatisgorund;
        void Awake()
        {
            inputMaster = new InputMaster();
            inputMaster.player.Enable();
            inputMaster.player.Jump.performed  = Jump;
            inputMaster.player.primaryuse.performed  = PrimaryUse;
            rig = GetComponent<Rigidbody>();
        }
        void Update()
        {
            inputVector = inputMaster.player.movement.ReadValue<Vector2>().normalized;
        }
        public void FixedUpdate()
        {
            isGrounded = Physics.CheckSphere(groundcheck.position, 0.5f, whatisgorund);
            Vector3 move = transform.right * inputVector.x   transform.forward * inputVector.y;
            transform.position = rig.position   speed * Time.deltaTime * move;
        }
    
        public void Jump(InputAction.CallbackContext context)
        {
            if (context.performed && isGrounded)
            {
                rig.AddForce(Vector3.up * 5, ForceMode.Impulse);
            }
    
        }
        public void PrimaryUse(InputAction.CallbackContext context)
        {
            if (isGrounded && context.performed)
            {
    
            }
        }
}

here is a screenshot of my player: player

CodePudding user response:

If an object is pushed through others largely depends on the physics engine being able to keep the minimun distances.

Furthermore, it keeps track of touching points.

Your FixedUpdate() directly changes transform.position. that usually breaks physics contacts when already touching. Do not do that. Try to work only with changes in speed - best by using AddForce(). (already included in your script as well)

Also, you did not provide more information about what you are squeezed into. If those are 'kinematic' objects, then you player cannot stop them and might also clip into. For example, a door squeezing you as a 'kinematic' object does not allow the player to stop the door. A rigibody under physics control can be stopped by the player in the way.

  • Related