this is my first project i am trying to get the player to collide with the wall in my game (2d) however despite using the same code i got from some tutorials in one of the projects the player passes through the wall entirely while in the other the player gets stuck even though its not supposed to.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public int speed;
public float horizontalInput;
public float verticalInput;
public float rotationSpeed;
private BoxCollider2D boxcollider;
private Rigidbody2D playerRB;
// Start is called before the first frame update
void Start()
{
boxcollider = GetComponent<BoxCollider2D>();
playerRB = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Movement();
}
private void Movement()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector2 movementDirection = new Vector2(horizontalInput, verticalInput);
RaycastHit2D castResult;
castResult = Physics2D.BoxCast(transform.position, boxcollider.size, 0, new Vector2(horizontalInput, 0), Mathf.Abs(horizontalInput * Time.fixedDeltaTime * speed), LayerMask.GetMask("enemy", "wall"));
if (castResult.collider)
{
movementDirection.x = 0;
}
castResult = Physics2D.BoxCast(transform.position, boxcollider.size, 0, new Vector2(0, verticalInput), Mathf.Abs(verticalInput * Time.fixedDeltaTime * speed), LayerMask.GetMask("enemy", "wall"));
if (castResult.collider)
{
movementDirection.y = 0;
}
playerRB.velocity = movementDirection.normalized * speed;
}
}
if anyone knows whats wrong that would be great
thanks