Question by
DarkShadowDevelopment · Aug 22, 2021 at 03:10 PM ·
collisionmovement scriptlayermaskrpg-game
Can someone help me fix this?
So when I tried to make it so when my character hits an npc (actor layer) / wall (blocking layer) hit can t pass it yk what i mean? But when i added like the hit part the character is only moving up and down even when i press arrow to left or right it goes up / down. What s wrong in the code?
Unity 2020
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private BoxCollider2D boxCollider;
private Vector3 moveDelta;
private RaycastHit2D hit;
private void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
// Reset moveDelta
moveDelta = new Vector3(x, y, 0);
// Swap Sprite Direction wether you're going right or left
if (moveDelta.x > 0)
transform.localScale = new Vector3(1, 1, 1);
else if (moveDelta.x < 0)
transform.localScale = new Vector3(-1, 1, 1);
// Make sure we can move in this direction, by castingg a box there first, if the box returns null we are free to move
hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Actor", "Blocking"));
if (hit.collider == null)
{
// Make this thing move
transform.Translate(0,moveDelta.y * Time.deltaTime, 0);
}
hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x,0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Actor", "Blocking"));
if (hit.collider == null)
{
// Make this thing move
transform.Translate(0, moveDelta.x * Time.deltaTime, 0, 0);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How do Contact Filters work? 1 Answer
Linecasting solution, without using layermasks. 1 Answer
Problem with moving and colliding 0 Answers
Limit of a move for position 1 Answer
Shopping Cart Movement 0 Answers