- Home /
Stop player running at wall
I have a simple script that tracks the input of the keys, and uses that to add some force to move them left and right:
using UnityEngine;
using System.Collections;
private Vector3 input;
private float moveSpeed;
public class PlayerController : MonoBehaviour
{
void Update()
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
rigidbody.AddRelativeForce(input * moveSpeed);
}
}
Now, I have two walls on the very right and left of the player. The issue here is that if the player jumps onto the wall, and keeps going in that direction, it will keep trying to move in that direction in the air. I am guessing this is because it is simply adding force to the object, making it move and in this case squash against the walls
Is there a way to remedy this? I thought of disabling movement until it reaches the ground, but then you simply can't move the opposite way, which could feel weird to some players.
when a player collides with a wall on the right side. If applied force is greater than zero change it back to zero. But if applied force is negative do not change it. Vice versa.
How would you actually code that? How do you check when the force is negative or not?
Answer by Priyanshu · Jan 09, 2015 at 10:06 AM
Tag wall objects as RightWall and LeftWall and try this script.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
private Vector3 input;
public float moveSpeed;
public bool touchRightWall, touchLeftWall; //Booleans to check if player is touching walls
void Update()
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
//If player is not touching any wall. Force can be added in both directions.
if(!touchRightWall && !touchLeftWall)
rigidbody.AddRelativeForce(input * moveSpeed);
//If player is touching wall on the right side. Force can only be added in '- x' direction.
if(touchRightWall )
{
if( input.x < 0)
rigidbody.AddRelativeForce(input * moveSpeed);
}
//If player is touching wall on the left side. Force can only be added in '+ x' direction.
if(touchLeftWall)
{
if( input.x > 0)
rigidbody.AddRelativeForce(input * moveSpeed);
}
}
void OnCollisionEnter( Collision other)
{
//Player is touching right wall
if( other.collider.tag == "RightWall")
{
touchRightWall = true;
Debug.Log("OnCollisionEnter");
}
//Player is touching left wall
if( other.collider.tag == "LeftWall")
{
touchLeftWall = true;
Debug.Log("OnCollisionEnter");
}
}
void OnCollisionExit( Collision other)
{
//Player is not touching right wall
if( other.collider.tag == "RightWall")
{
touchRightWall = false;
Debug.Log("OnCollisionExit");
}
//player is not touching left wall.
if( other.collider.tag == "LeftWall")
{
touchLeftWall = false;
Debug.Log("OnCollisionExit");
}
}
}