- Unity 4.x Game Development by Example Beginner's Guide
- Ryan Henson Creighton
- 354字
- 2025-03-31 04:02:11
Time for action – animate the Paddle
The changes are very subtle. We added a plus sign (+
) before the equals to sign (=
), and we made the number smaller by adding a zero and a decimal place in front of it, changing it from 2
to 0.2
.
Save the Script and test your game. The Paddle should scoot out the way, and fly straight off the right-edge of the screen!
What just happened – what witchcraft is this?
We made the 2
smaller, because the Paddle would have just rocketed off the screen in a twinkling and we may not have seen it. But, there's a tiny bit of code magic going on in that +=
bit.
By changing the transform.position.x
property with +=
instead of =
, we're saying that we want to add 0.2
to the x
property on every update. The special built-in Update
function automatically gets called again and again by Unity as your game plays. While this happens, the x
position constantly increases. Let's follow the following logic:
- The first time
Update
is called,x
is 0. We add0.2
, and the Paddle moves to0.2
. - The second time
Update
is called, x is0.2
. We add0.2
, and the Paddle moves to0.4
. - Every time
Update
is called, the Paddle'sx
position increases. We get a real sense of how often theUpdate
function is called by how quickly the Paddle moves across the screen in tiny0.2
increments.
Tip
Any excuse to work less
+=
is a bit of programmer shorthand. It's the same as typing:
transform.position.x = transform.position.x + 0.2;
But that's way more typing, and the less you have to type the better. Excessive typing kills 80 percent of computer programmers before their 40th birthdays. I just made that stat up, so it's probably off by a few percentage points.