Sunday, September 17, 2017

Unity 3d auto-move player forward script


Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get.


I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m/s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls)



Thank you!



Answer



The first sample code is what you want. http://unity3d.com/support/documentation/ScriptReference/Transform.Translate.html


function Update() 
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * Time.deltaTime);
}

Vector3.forward is the same as (0,0,1), and transform.Translate() is local translate, so Translate(0,0,1) is always moving forward. Time.deltaTime let speed equal to 1 m/s.


And you can change the default key in "Input Manager" http://unity3d.com/support/documentation/Components/class-InputManager.html



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...