- Home /
Raycasting not working as expected: rays are perpendicular to projectile's trajectory and collision doesn't occur
Hi,
I'm having a problem with raycasting and object colliding and not a clue what it is. It's difficult to explain, so I've uploaded my sample project. This is the link:
https://drive.google.com/open?id=0B8Gqj5xq7RSnaUlGNjFUM0JJcVE
The problem is the following: when the player gameObject shoots a bullet, the ray the bullet casts is perpendicular to the bullet instead of being in the same path as the bullet. That causes the collisions not to work as expected.
This is a screen capture of the view from above that shows what I'm talking about.
I thought that how the projectile's ray was being instantiated in the Projectile.cs class (line 93) could be the problem. So I tried changing that from this...
Ray ray = new Ray (transform.position, transform.forward);
to this... Ray ray = new Ray (transform.position, Vector3.forward);
When doing that, the enemy diagonal to the player is actually hit. BUT the enemy that's positioned in z=0 isn't: the bullet just goes through him.
Again, not sure why the raycasts are perpendicular to the bullet's trajectory. I guess that's the problem but not sure why it happens.
Any ideas? Thanks in advance!
Ray ray = new Ray (transform.position, transform.forward);
Is this a 2D game? Then try transform.right. If it's a 3D game make sure the bullet object points in the right direction, the blue arrow in the editor shows the "forward" vector.
Answer by kkrac · Jan 17, 2017 at 01:54 PM
Thanks @doublemax
Yes, some minutes later after posting the question, I tried transform.right and it worked. It is a platformer with an ortographic camera, but I work with the "z" axis too to shoot enemies not only sideways but also in the distance.
I will check the projectile is pointing in the right direction. I was pretty sure it was, but I will double check.
dumb question: in a 2d game doesn't the projectile have to point to its forward vector too, which would be to the right of the screen? In which case, transform.forward shouldn't it work in that case?
I don't know what exactly Unity does in the background in 2D mode, but in general it's the same 3D engine running. $$anonymous$$y guess is that transform.forward always points in Z direction.