Moving rigidbody (Player) with addForce or Velocity ?

Hello, I have a big question.


I am trying to move the player (Rigidbody).
My problem is when I move the player(Rigidbody) and the player touches a wall the player starts to spin and fly in a random direction and player canˇt control this.


I have tried using AddForce,Velocity and MovePosition but there is either no movement or movement that ends up in the player launching into random direction with increasing speed.


My question is what would be the best way of moving the player or fixing this issue ?
I have tried reading through Unity Documentation but there isnˇt enough information.

This is my script that I use for movement.

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

[RequireComponent(typeof(Rigidbody))]
public class Hrac_POHYB : MonoBehaviour
{
    public float movementSpeed;
    public float walkingSpeed;
    public float runningSpeed;

    public bool isSprinting;
    Rigidbody rgBody;

    float inputX;
    float inputY;

    Vector3 input;
    Vector3 inputDir;
    Vector3 moveAmount;
        
    void Start()
    {
        rgBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        GetInput();

        if (isSprinting) { movementSpeed = runningSpeed; } else { movementSpeed = walkingSpeed; }

        input = transform.right * inputX + transform.forward * inputY;
        inputDir = input.normalized;
        moveAmount = (inputDir * movementSpeed);
    }

    private void FixedUpdate()
    {
       // rgBody.velocity = moveAmount * Time.deltaTime;  //No movement
       // rgBody.velocity = moveAmount * Time.fixedDeltaTime;  //No movement
        rgBody.velocity = moveAmount; //Movement but launch upon collision
    }


    void GetInput() 
    {
        inputX = Input.GetAxisRaw("Horizontal");
        inputY = Input.GetAxisRaw("Vertical");
        isSprinting = Input.GetKey(KeyCode.LeftShift);
    }
}

Keep on using player.velocity as your code is but add an OnCollisionEnter() void to freeze rotation when entering collision with a wall. You will have to add a tag to all your walls as walls or whatever you want.

void OnCollisionEnter(Collision coll){
    if(coll.gameObject.tag == "wall(or whatever)"){
        player.freezeRotation = true
    }
}

And then use OnCollisionExit the same way but set player.freezeRotation to false. Hope this helps :smiley: