Game Development Reference
In-Depth Information
Rule #2 - motion must be relative to time
As you cannot guarantee the frequency of frames (frame rate differs over time
and across computers), then you need to code motion and change very carefully to
achieve a consistent experience for the gamer. Consider the simple case of moving a
cube object in the scene smoothly over time. One way (a bad way) to create motion
will be as shown in the following code sample 3-10:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour
{
//Amount to move cube per frame
public float AmountToMove = 1.0f;
// Update is called once per frame
void Update ()
{
//Move cube along x axis
transform.localPosition += new Vector3(AmountToMove,0,0);
}
}
This code is effective insofar as it will move the attached object by the variable
AmountToMove on each frame. The problem is that it's frame-rate dependent. Now,
because frames are inconsistent over time and across computers, each user will
ultimately receive a different experience; specifically, they'll see the cube moving at
different speeds. This is bad because we simply cannot predict how the game will
run for any specific user. To fix this, we need to map motion to time as opposed
to frames. Frames are variable, but time is constant; one second is exactly that.
To achieve this, we can use the deltaTime variable, which is part of the Time class.
See the following code sample 3-11. This is an amended version of sample 3-10.
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour
{
//Speed of cube
public float Speed = 1.0f;
// Update is called once per frame
void Update ()
{
 
Search WWH ::




Custom Search