I've been trying to learn how to use Raycast2D for days and I'm not able to, I want my raycast to detect when it has collided with an NPC to make some kind of interaction system, but as much as I try the maximum progress I've managed to make is that the raycast works in the direction it should but not the distance, it always reports on screen that it has found the limit map collider, even if I rotate on myself to detect any other collider, first of all thank you very much for reading and for your effort! <3
private void Update() {
movimiento();
if (posesion) {
Debug.Log("ENCONTRADO");
}
hit = Physics2D.Raycast(transform.position, transform.position direccion2 * 500, 0);
Debug.DrawRay(transform.position, transform.position direccion2 * 500, Color.red);
if (true) {
Debug.Log(hit.transform.name);
}
if (hit.transform.tag == "NPC" && !posesion) {
Debug.Log("Estamos dentro");
if (Input.GetButtonDown("Fire2")) {
timer = Time.time;
}
if (Input.GetButtonUp("Fire2")) {
timerB = Time.time;
if (timerB - timer >= 3) {
timer = 0;
timerB = 0;
hit.transform.gameObject.GetComponent < NPC > ().turnPosession();
startPossesion();
}
}
}
}
The firsts lines of the code
[SerializeField]
private float velocidadMovimiento;
[SerializeField]
private Vector2 direccion;
private Vector3 direccion2;
private Rigidbody2D rb2D;
private float movimientoX;
private float movimientoY;
private Animator animator;
private bool posesion;
private float timer, timerB;
private RaycastHit2D hit;
private void Start() {
animator = GetComponent < Animator > ();
rb2D = GetComponent < Rigidbody2D > ();
posesion = false;
timer = 0;
timerB = 0;
}
private void movimiento() {
movimientoY = Input.GetAxisRaw("Horizontal");
movimientoX = Input.GetAxisRaw("Vertical");
animator.SetFloat("MovimientoX", movimientoX);
animator.SetFloat("MovimientoY", movimientoY);
direccion = new Vector2(
Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical")
).normalized;
if (movimientoX != 0 || movimientoY != 0) {
direccion2 = new Vector3(
Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical"), 0
).normalized;
animator.SetFloat("UltimoX", movimientoX);
animator.SetFloat("UltimoY", movimientoY);
}
}
CodePudding user response:
This part is wrong:
hit = Physics2D.Raycast(transform.position, transform.position direccion2 * 500, 0);
It should be:
hit = Physics2D.Raycast(transform.position, direccion2, 500);