I'm currently trying to have a raycast detect the player caracter to have an event happen when a specific key is pressed here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class action: MonoBehaviour
{
public float dist;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
RaycastHit2D down = Physics2D.Raycast(transform.position, -Vector2.up, dist);
Debug.Log(transform.position);
if (Input.GetKeyDown(KeyCode.Z) == true && down.collider != null)
{
Debug.Log("hi");
}
}
}
I'm basicly trying to make a small raycast,which is why I place a distance instead of letting it go infinitely, and have it so if the raycast is triggered and the player presses z the event happens(which for now is the debug console), but all it does now is triggers whenever I press z no matter where the player caracter is. I tried drawing the raycast but I can't seem to make it work.
CodePudding user response:
I think the reason for that is that the raycast is hitting the object containning the script it self and so the collider is allways non null try adding a LayerMask that differs from the GameObject's Layer
so it's something like this :
RaycastHit2D down = Physics2D.Raycast(transform.position, -Vector2.up,
dist , 1 << /*The Target's Layer*/);
You can find the layer in the up left corner of your inspector when you click on a GameObject
CodePudding user response:
Head to the Unity Documentation for LayerMask for more details.