Last active
December 29, 2015 08:29
-
-
Save poemdexter/7644211 to your computer and use it in GitHub Desktop.
Quick explanation of unity movement via transform manipulation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code in question: | |
transform.position += transform.right * Input.GetAxis(axisName) * speed * Time.DeltaTime; | |
transform.position | |
position vector of the entity this script is attached to | |
transform.right | |
vector representing "right" relative to this entity's rotation. normally is <1,0,0>. for example, | |
you have no rotation and are facing forward. your "right" would be <1,0,0>. if you turn 180 | |
degrees, your "right" would be <-1,0,0>. | |
Input.GetAxis(axisName) | |
gets value between -1 and 1 for the axisName in question ("Horizontal" or "Vertical"). axisNames | |
are changable in Unity Input Settings. For keyboards, it's usually 0 or 1 or -1. You can get | |
"half keystrokes" via Input.GetRawAxis(axisName). | |
speed | |
speed is usually a seperate variable because it determines the magnitude of the movement vector. | |
Time.DeltaTime | |
amount of time passed between frame updates. a good way of keeping things framerate independent | |
while still running as fast as user allows. for physics that need to be deterministic, it's better | |
to use FixedUpdate() instead of Update(). | |
ref => http://docs.unity3d.com/Documentation/ScriptReference/Time-deltaTime.html | |
= poem's notes = | |
transform.position += transform.right * Input.GetAxis(axisName) * speed * Time.DeltaTime; | |
- can be rewritten as - | |
transform.translate(Vector3.right * Input.GetAxis(axisName) * speed * Time.DeltaTime); | |
Translate() will move everything relative to the entities local axes meaning no matter how you are | |
rotated, moving "right" will always move you in correct "right" direction. Vector3.right returns <1,0,0> | |
always and is fine here and saves you from hitting transform component to calculate transform.right | |
(premature optimization whoo!) | |
ref => http://docs.unity3d.com/Documentation/ScriptReference/Transform.Translate.html | |
= examples of move code = | |
(Western Game) | |
https://github.com/poemdexter/Western-Shooter/blob/master/Assets/Scripts/Mobs/PlayerMovement.cs | |
3D Game with WASD movement. Get each axis seperately and then translate it to correct axis | |
(x left/right, z forward/back) | |
(Kids Bop) | |
https://github.com/poemdexter/2DToolkit-Game/blob/master/Assets/Assets/Scripts/PlayerMovement.cs | |
2D Game with variable jump height. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment