- Home /
Question by
ayockel90 · Feb 14, 2019 at 10:24 PM ·
scripting problemraycasthit2d
RaycastHit2D not printing name of collider
I have a basic RaycastHIt2D that works, but thinks everything it's hitting is the Player object.
public class Shooting : MonoBehaviour {
public GameObject Player;
void Update(){
//Hold right click and press left click to shoot
if(Input.GetMouseButtonDown(0) && Input.GetMouseButton(1)){
Shoot();
}
}
void Shoot(){
Vector2 startPos = Player.transform.position;
Vector2 beamDirection = Player.transform.up * 10;
//Show laser beam
Debug.DrawRay (startPos, beamDirection, Color.green, .05f);
//Detect and log hits
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.up);
if(hit.collider != null){
Debug.Log(hit.transform.name + " was hit");
}
}
}
No matter what I shoot, it says Player was hit, but the object it's colliding with is a tilemap. Am I missing something?
Comment
try?
RaycastHit2D hit = Physics2D.Raycast(Player.transform.position, Player.transform.up);
Best Answer
Answer by James_BadAlchemy · Feb 15, 2019 at 03:48 AM
If you're shooting it from inside the player's collider then it's probably hitting it. Try moving it down to setting up a layermask.
Ended up not worrying about it since it won't affect the game, but had to use RaycastAll to get it to register hitting other objects
RaycastHit2D[] hits = Physics2D.RaycastAll(Player.transform.position, Player.transform.up);
Your answer