I’m looking to have a character accelerated when moving forward, decelerate when movement keys aren’t pressed (keyboard/joystick), and slide when on certain surfaces.
I have managed to accelerate the player, but I’m having issues with the deceleration.
I assume is because I’m multiplying the moveDirection Vector’s forward and right (z and x) by Input.GetAxis (which becomes 0 when they are let go.)
After that I’ll know how to code in the friction.
I’ve attached the segments of my player script that deals with movement exclusively. This is for a 3D platformer by the way, similar to Mario 64/Galaxy.
Any help would be wonderful. Thanks in advance!
//=====================================================================
// CalculateMovement
//=====================================================================
function CalculateMovement()
{
var jumpButton = Input.GetButton("Jump");
var jumpButtonPressed = Input.GetButtonDown("Jump");
var dodge = Input.GetKeyDown(KeyCode.DownArrow);
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
y = moveDirection.y;
if (x != 0 || z != 0)
isMoving = true;
else if (x == 0 && z == 0)
isMoving = false;
horizontalSpeed = horizontalVelocity.magnitude;
verticalSpeed = controller.velocity.y;
overallSpeed = controller.velocity.magnitude;
var cameraTransform : Transform = Camera.main.transform;
var forward : Vector3 = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
var right = Vector3(forward.z, 0, -forward.x);
if ((!isAttacking) && canMove && isMoving)
{
moveDirection = x * right + z * forward;
}
if (moveDirection != Vector3.zero)
{
curSpeed += speed * Time.deltaTime;
curSpeed = Mathf.Clamp(curSpeed,0,maxSpeed);
}
if (!isMoving && canMove)
{
curSpeed -= (friction) * Time.deltaTime;
if (curSpeed < 0)
curSpeed = 0;
}
}
//=====================================================================
// ApplyMovement
//=====================================================================
function ApplyMovement()
{
// Move the controller
if (!busy))
{
var recalcMoveDir : Vector3 = Vector3(moveDirection.x,0,moveDirection.z)*curSpeed;
recalcMoveDir.y = moveDirection.y;
controller.Move((recalcMoveDir) * Time.deltaTime);
}
}