I’ve written a simple movement script using transform.translate, and I’m using raycasts to determine if the player is touching a wall or not. The problem is the player sometimes clips into the wall before movement is stopped, and it seems to be completely random whether the player clips in or not. I’m still fairly inexperienced, and I have no idea what’s causing the issue. Any help would be greatly appreciated.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
//Variables
//Movement
Vector3 velocity;
//Left and Right Movement
private float move = 0f;
public float MaxSpeed = 5f;
//Jumping
private bool jump = false;
//Raycasting
private bool Twall = false;
private bool Bwall = false;
Rect PlayerBox;
Vector2 TopC;
Vector2 BotC;
//layermasks
private int DefaultMask;
//animation
// Use this for initialization
void Awake ()
{
DefaultMask = 1 << LayerMask.NameToLayer("Default");
}
void Start ()
{
}
// Update is called once per frame
void Update ()
{
//input
move = Input.GetAxisRaw("Movement");
//raycast origin points
PlayerBox = new Rect( //storing the size of the player's hitbox
collider2D.bounds.min.x,
collider2D.bounds.min.y,
collider2D.bounds.size.x,
collider2D.bounds.size.y);
TopC = new Vector2(PlayerBox.center.x,PlayerBox.yMax);
BotC = new Vector2(PlayerBox.center.x,PlayerBox.yMin);
//debug
Debug.Log (velocity.x);
}
void FixedUpdate ()
{
velocity = new Vector3 (velocity.x,0,0);
velocity.x = move * Time.deltaTime * MaxSpeed;
Twall = Physics2D.Raycast(TopC,Vector2.right * move,(0.05f + PlayerBox.width/2),DefaultMask);
Bwall = Physics2D.Raycast(BotC,Vector2.right * move,(0.05f + PlayerBox.width/2),DefaultMask);
if(Twall || Bwall)
{
MaxSpeed = 0f;
}
else
{
MaxSpeed = 5f;
}
}
void LateUpdate ()
{
transform.Translate(velocity);
}
}