Search code examples
c#unity-game-engineraycast

Unity Collision Detection with Raycasts off center


I was making a 3D game in Unity, and I was setting up a collision detection system with raycasts, and it seemed off center.

My code was:

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

public class Player : MonoBehaviour {
    [SerializeField] private float movementSpeed = 7f;
    [SerializeField] private float rotationSpeed = 10f;
    [SerializeField] private float playerSize = .7f;

    [SerializeField] private GameInput gameInput;

    private bool isWalking;

    private void Update() {
        Vector2 inputVector = gameInput.GetMovementVectorNormalized();

        Vector3 moveDir = new Vector3 (inputVector.x, 0f, inputVector.y).normalized;

        bool canMove = !Physics.Raycast(transform.position, moveDir, playerSize);

        if (canMove) {
            transform.position += moveDir * movementSpeed * Time.deltaTime;
        }

        isWalking = moveDir != Vector3.ze
        transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime *      rotationSpeed);
    }
}

I tried changing the player size, but it wouldn't let me go past a point which was about an inch away from the cube I was using to test. On the other side, I could go into the cube, but not all the way.


Solution

  • By default, the raycast starts at the player's pivot point (which is usually at the center of the GameObject). This can lead to a situation where the raycast is slightly off from what you'd expect, causing inconsistent collision detection.

    Adjust Origin according to Player Size:

    bool canMove = !Physics.Raycast(transform.position + Vector3.up * 0.5f, moveDir, playerSize);
    

    Or you can use SphereCast.