0
\$\begingroup\$

I'm making a simple character controller. Each frame the player moves by moveDistance units in the moveDir direction.

I'm casting a capsule to detect any collision:

private void Update() 
{
    Vector2 input = _gameInput.GetGameInputNormalized();

    Vector3 moveDir = new Vector3(input.x, 0, input.y);
   
    float moveDistance = moveSpeed * Time.deltaTime;
    bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * 2f, .7f, moveDir, moveDistance);

    Debug.Log(canMove);

    if (canMove)
    {
        transform.position += moveDir * moveDistance;
        IsWalking = true;
    }
    else
    {
        IsWalking = false;
    }   

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

It's working as expected but with one problem. Printing canMove when the user is colliding with a wall and still trying to move towards it prints a mix of True and False as shown here:

Gif showing true and false logs

Note that the player is still moving towards the wall when the console is printing both True and False.

I've tried removing the rotation logic, increasing the capsule cast distance but nothing worked.

One thing I suspected was the need to use Unity's FixedUpdate method, but it also didn't work.

\$\endgroup\$
2
  • \$\begingroup\$ Does your last paragraph means it solved the problem and you don't know why or do you think that's a fix but are not sure if it is? \$\endgroup\$
    – Zibelas
    Commented Feb 19, 2023 at 15:01
  • \$\begingroup\$ @Zibelas No it didnt fix the problem. Will edit the question to clear that up \$\endgroup\$
    – EEAH
    Commented Feb 19, 2023 at 15:33

1 Answer 1

0
\$\begingroup\$

It was actually a small bug where the class was mistakenly attached to 2 game objects. And that is because there is a class responsible for animations that is attached on the graphics game object of the player. That class had the attribute: [RequireComponent(typeof(Player))] where Player is the class that is printing to the console.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ A good trick to find these types of issues faster in the future: before posting on StackExchange, take a moment to build a Minimal Complete Verifiable Example. That is, make a new empty project with just the script you want to test, on a single object. If the problem doesn't manifest in that test case, then you know there's something funny about your original scene (like having two copies of the script). Even if this doesn't reveal the problem instantly, it can help you identify the necessary details to include in your question, since you'll have tested and verified that it's reproducible. \$\endgroup\$
    – DMGregory
    Commented Feb 19, 2023 at 17:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .