Raycast not detecting a gameobject.
I have 2 objects that are spawning randomly on the plane, a rock and a tree, both have colliders and rigidbodys, they are both tagged as "breakable", but, when im playing and i click on a tree, in the console it says "hit" and "breaking..." as it should, but when i click on a rock nothing happens. any help is appreciated!
I have this code inside my player script:
void Attack()
{
if (Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
if (Physics.Raycast(cam.transform.position, transform.TransformDirection(Vector3.forward), out hit, attackDistance))
{
Debug.Log("Hit");
if(hit.collider.tag == "Breakable")
{
ObjectHealth objHealth = hit.collider.gameObject.GetComponent<ObjectHealth>();
objHealth.TakeDamage(25);
Debug.Log("breaking...");
}
}
}
}
Answer by unity_ek98vnTRplGj8Q · May 21, 2020 at 10:01 PM
Make sure your rock is not in the "Ignore Raycast" layer... also you are using your camera's position but your player's forward direction to cast the ray. Depending on your setup its possible that you are looking down with your camera but not down with your player, and your raycast is missing because it is going straight out rather than down like you expect. It may help to use Debug.DrawRay() to draw the same ray that you are casting in the scene so that you can make sure it looks like what you want
thank, i realized i put the origin of the ray at the camera but didnt make the direction from the camera. Thanks!
Your answer
Follow this Question
Related Questions
RayCast2D and RayDraw errors 0 Answers
Inheritence problems with raycast 1 Answer
Make raycast ignore hitbox? 0 Answers
Swipe single object at a time upon touch, not swiping allover the screen 0 Answers
BulletHole and HitSparks spawning in front of weapon 0 Answers