Help with getting my player to stop moving when they hit a wall?
Hey, so I am new to unity, and am having problems with my player going through walls when I tell the player to move. The game is just basic movement inside of a room right now.
Here is the code that I am using for the playercontroller: using UnityEngine; using System.Collections;
 public class Player : MonoBehaviour {
     public float speed = 0.1f;
     //holds which key is currently being pressed (none if none)
     private KeyCode keyPressed;
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
 
         //move right
         if(Input.GetKey(KeyCode.RightArrow) && keyPressed == KeyCode.None
            || Input.GetKey(KeyCode.RightArrow) || keyPressed == KeyCode.RightArrow) 
         {
             transform.position += transform.right * speed;
             keyPressed = KeyCode.RightArrow;
         }
 
         //move left
         if(Input.GetKey(KeyCode.LeftArrow) && keyPressed == KeyCode.None
            || Input.GetKey(KeyCode.LeftArrow) && keyPressed == KeyCode.LeftArrow) 
         {
             transform.position += -transform.right * speed;
             keyPressed = KeyCode.LeftArrow;
         }
 
         //move forward
         if(Input.GetKey (KeyCode.UpArrow) && keyPressed == KeyCode.None
            || Input.GetKey(KeyCode.UpArrow) && keyPressed == KeyCode.UpArrow) 
         {
             transform.position += transform.forward * speed;
             keyPressed = KeyCode.UpArrow;
         }
         //move backward
         if(Input.GetKey (KeyCode.DownArrow) && keyPressed == KeyCode.None
            || Input.GetKey(KeyCode.DownArrow) && keyPressed == KeyCode.DownArrow)  
         {
             transform.position += -transform.forward * speed;
             keyPressed = KeyCode.DownArrow;
         }
 
         if(Input.GetKeyUp(keyPressed)) {
             keyPressed = KeyCode.None;
         }
     }
 }
I might be wrong on this, but I think I experienced something similar when I was starting out. I think it may help to put the movement code inside of FixedUpdate() ins$$anonymous$$d.
Answer by NullOverrideX · Oct 21, 2020 at 07:21 AM
Maybe try using Rigidbody, then when you hit a wall, put the Rigidbody component to sleep.
Here, use this:
 GetComponent<RigidBody>().Sleep();
Hope this helps, but I'm just 9 and started Unity a few months ago. I found this online
Edit: Oop, just realized you posted this five years ago
Your answer
 
 
             Follow this Question
Related Questions
Rigidbody going through Colliders help! 1 Answer
Rigidbody sticks to wall 0 Answers
[Help] Player stops moving when hitting wall diagonally 0 Answers
Character Leaning 0 Answers
Camera collision with mesh object 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                