- Home /
How Do I move my main character?
So this sounds like i'm so stupid and all that, but it's now, I'm just new. Can someone please help me write a basic code for moving an object (lets say a cube or a sphere, third-person or first-person, it doesn't matter)
Answer by Peter G · Apr 08, 2010 at 01:26 AM
See the FPS controller that comes in the standard assets and check the tutorials for useful controller scripts. Unity Resources Page
And here's the FPS walker script.
var speed = 6.0; var jumpSpeed = 8.0; var gravity = 20.0;
var rotateSpeed : int; //the base controller does not use this, but it is helpful for rotations.
private var moveDirection = Vector3.zero; private var grounded : boolean = false;
function FixedUpdate() { if (grounded) { // We are grounded, so recalculate movedirection directly from axes moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// Apply gravity moveDirection.y -= gravity * Time.deltaTime;
// Move the controller var controller : CharacterController = GetComponent(CharacterController); var flags = controller.Move(moveDirection * Time.deltaTime); grounded = (flags & CollisionFlags.CollidedBelow) != 0; }
@script RequireComponent(CharacterController
To rotate instead of strafe, change this:
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
to this:
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
and add this:
transform.Rotate(0, Input.GetAxis("Horizontal") * RotateSpeed * Time.deltaTime, 0);
after var flags = controller.Move(moveDirection * Time.deltaTime);
Nitpicking perhaps, but your modification doesn't really work. If you do it like that it rotates the model, but the CharacterCcontroller moves forward and backward along the world Z axis, not along the rotated local Z axis.
I tested them and they do. The only error I found was a small typo. RotateSpeed should be rotateSpeed. The compiler wouldn't let that compile though so it wouldn't matter. transform.TransformDirection makes sure that the character rotates relative to local space, not world space.
Your answer
Follow this Question
Related Questions
auto run key 1 Answer
FPShooter sideway/forward dash? 1 Answer
Why doesn't this motion script work? 2 Answers
Networking Synchronize Problem. 0 Answers
Making player movement none dependent on mouse position 1 Answer