- Home /
Moving Forward
Hi,
I was wondering what javascript code you can use to make a character go forward when the player hits "W", and back when he presses "S", and turns when he presses "A" or "D". Please comment the code so that I can see what makes what work.
Thank You for Your Time
Answer by Berenger · Feb 10, 2012 at 09:44 PM
Go in Asset->IMport Asset->Character Controller. Drag the 1st or 3rd Person Controller prefabs into your scene, play around, then look the scripts 3rd or FPSInputController. It's completely commented, but there is a lot to do. So grab a coffe, tell your friends they won't see you for a while, and go for it !
Thank You, but I have a kind of personality characteristic. The Reason that I decided to use Unity ins$$anonymous$$d of Blender for game engine, is because that I don't like to use things that were made by someone else, because it feels like I am just slapping on code. I like to write my own code. Now this might seem a little stupid, because I was asking for someone to write a piece of javascript for me, but I wanted a simple script that I could mess around with. You did not know this, so thank you for your help.
Fair enough. So let's focus on the heart of those script I was talking about. Their point is to make the movement smooth, control the jump, the collisions, the animations and other stuff. If you just want the movement, it's pretty simple (Yihaaa, I managed the code formatting in a comment !!) :
var speed : float = 100f;
function Update(){
var v, h : float;
v = Input.GetAxis( "vertical" ); // Up and down button
h = Input.GetAxis( "horizontal" ); // Left and right
if( $$anonymous$$athf.Abs(v) > 0f || $$anonymous$$athf.Abs(h) ){ // Is the player pressing a key ?
var direction : Vector3;
direction = Vector3( h, 0, v ).normalized;
// Set the direction in local space. The rotation isn't implemented here
direction = Transform.InverseTransformDirection( direction );
direction *= speed * Time.deltaTime; // Adjust speed
transform.position += direction; // Classique
characterController.Simple$$anonymous$$ove( direction ) // CharacterController. Use only one ;)
}
}
That is good for my purposes, But is there a way to specificly "say" that a certain key triggers a certain fuction? Thank You
It's not possible natively to map a function on a key. However, you can know if a key is pressed or not with the Input class. If you get a positive, you can call the corresponding function.
Your answer
Follow this Question
Related Questions
"Teleport" in the way the player is heading 2 Answers
How can I tell Unity to wait to do something until after and animation has finished playing? 1 Answer
Problem with PlayerHealth and renderer 1 Answer
How can I activate a script upon entering an area? 1 Answer
Basic Movement on a Plane without Character Controller 2 Answers