Game Development Reference
In-Depth Information
Now not all of these parameters must be expressed; however, if they are,
they have to be laid out in the order listed there. So, for instance, the line
of code:
Physics.Raycast (transform.position, transform.forward,
hit, 100);
means, “Cast a ray. As its origin, use the position of the object this script is
attached to (transform.position). For the direction, cast the ray along the
object's Z-axis (transform.forward, which is really shorthand for 'along the
Z-axis'). Keep track of what we hit in the variable 'hit' and cast the ray 100 units
out—ignore everything further away than that.” That's a lot of information in
one line of script, no?
Now of course that line of script by itself is pretty useless. And in fact if it were
just floating around in a script it would be fired once and therefore be pretty
useless. However, if we told it to do that every frame we could start to gather a
lot of information.
So consider the following function:
function Update () {
var hit : RaycastHit;
Physics.Raycast (transform.position, transform
.forward, hit, 100);
}
function Update() just says, “do the things within the {} every frame.”
var hit : RaycastHit just declares that we want to keep track of the
RaycastHit with a variable called “hit.” Technically, this could go way up at
a higher level and we could declare this variable at the top of the script,
but since it is absolutely only going to be accessed within the raycasting
mechanism, declaring the hit variable here helps keep relevant ideas
together. Then comes the power line of code starting with Physics.Raycast.
What this block of code is doing is always shooting out a ray that looks in
the same direction as whatever this code is attached to (like a camera). The
ray is keeping track of what it's hitting (via the RaycastHit), which we can
use later.
And all of that comes from that Scripting Reference. It may still be a little
abstract here, so let's get going in some tutorials to look at how to use this
newfound knowledge.
Tutorial 14.1: Highlighting Actionable
Objects with Raycasting
The first tutorial we're going to use raycasting for is to highlight an object
that can be acted upon. Specifically, in this game we have a key that needs
to be picked up and a power main switch that needs to be thrown. In games
Search WWH ::




Custom Search