Sunday 30 November 2014

'Look at Object' mechanic - using Raycasting

Ok so this has a lot less math and a lot more fidgeting around with the engine. The end result is a lot less code as I depend on the engine to do most of the brunt work.

I never used Raycasting before, so I made use of the Unity video tutorial (found here). And as always the Unity API references.

It seemed pretty straight forward and it was. The most trouble I had was adjusting my Raycast to work well with my world. I ran into the following Hicups:

  • My Ray was attached to my camera, as this is what I was looking around with. The cube infront of my camera would get in my way and constantly block all other collision my ray might have encountered. The same issue happened to my Respawn-boundary I set up.

To fix this I added the planets to a separate layer and used to optional arguments to ignore everything outside of this layer. As an added precaution I instantiate the ray at the (cameras position)*2 to avoid the cube entirely so this would fix the issue regardless of layers.

My ray was defined as: 
Ray ray = new Ray(gameObject.transform.position*2, gameObject.transform.forward);

And my collision check was done as:
if(Physics.Raycast(ray, out hit, 500, 9)) [...] Where 500 was the length of the ray and 9 was the layer to avoid.

  • At first I was using Mathf.Infinity as the rays distance, but found it tricky to use with the debug visual I had set up (to see the raycast in-engine while running). 

As such I changed the distance from infinity to 500. This made the debugging code work and I could see the raycast properly.

Raycast being shown in-engine while run

Debug code:
Debug.DrawRay(transform.position, gameObject.transform.forward*500);

One final snag was where I was updating a value in the wrong method (not per frame) which meant the raycast wouldn't rotate with the camera. A minor oversight which I quickly fixed and the final result was a new "Look at object" mechanic that used raycasting.

This method of work is a lot easier to use as I use the engine to do a lot of the work for me. At the moment it's a bit to precise with the raycast, meaning I have to center the camera exactly at the right spot. I could fix this by tweaking the collision boxes.

However as this is just a prototype and we have yet to build the actual assets for use, this will not require tweaking until later.

No comments:

Post a Comment