Issue with RaycastHit2D and object collider
Hello, I'm pretty new with raycasting in Unity.
I was working on a grid base movement for a 2D game and I tryed to write a test code to figure out how to predict if in the next "cell" of the grid there would be a block with a BoxCollider2D attached (like a wall).
The code I wrote works fine but when the Player moves sometimes return a raycast collision that doesn't exist with objects placed at different global coordinates.
I can't find any fixes to this problem and I don't know where I'm wrong, if someone can help me I'll be very grateful, thank you.
The script needs to be attached to a empty GameObject with only a RigidBody2D set to "Dynamic", "Gravity Scale = 0" and Freeze Rotation enabled.
The Player moves by 1U per axis Input and the box colliders, of the Objects (like the walls), needs to be size of 1 by 1.
I'm using Unity 3D 2019.2.9f1
"Player" script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Vector2 nextPosition;
public Vector2 targetPosition;
public float movementSpeed = 10.0f;
private Rigidbody2D rb2D;
private BoxCollider2D bc2D;
private bool isAxisInUse;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
//bc2D = GetComponent<BoxCollider2D>();
isAxisInUse = false;
targetPosition = new Vector2(rb2D.position.x, rb2D.position.y);
nextPosition = new Vector2(rb2D.position.x, rb2D.position.y);
}
void FixedUpdate()
{
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
{
if (Input.GetAxisRaw("Horizontal") > 0 && isAxisInUse == false)
{
isAxisInUse = true;
nextPosition = nextPosition + new Vector2(1, 0); //set the next position where the Player wants to move
}
else if (Input.GetAxisRaw("Horizontal") < 0 && isAxisInUse == false)
{
isAxisInUse = true;
nextPosition = nextPosition - new Vector2(1, 0);
}
if (Input.GetAxisRaw("Vertical") > 0 && isAxisInUse == false)
{
isAxisInUse = true;
nextPosition = nextPosition + new Vector2(0, 1);
}
else if (Input.GetAxisRaw("Vertical") < 0 && isAxisInUse == false)
{
isAxisInUse = true;
nextPosition = nextPosition - new Vector2(0, 1);
}
}
else isAxisInUse = false;
RaycastHit2D hit = Physics2D.Raycast(nextPosition, nextPosition); //spawn raycast inside the "nextPosition" grid.
if (hit.collider != null) //if a raycast hits a collider
{
Debug.Log("Collider at " + hit.point + " " + hit.collider.name);
nextPosition = targetPosition; //set "nextPosition" as the current position of the Player -> the player won't move
}
else
{
targetPosition = nextPosition; //update the target position for the Vector2.MoveTowards
rb2D.position = Vector2.MoveTowards(transform.position, targetPosition, Time.deltaTime * movementSpeed); //move the rb2d towards the target position
}
}
}