Question by
harutoakiyama20 · Aug 15, 2020 at 07:35 AM ·
3dplayercontroller
unity3d player controlls not working sometimes
Hello, I've been trying to make an endless runner game but after every 2~3 lane movement/jump/sliding the player object which has a character controller, I need to swipe it twice or thrice to make it work again. And the player object seems like animation glitch moving the y axis by itself whenever the sliding the command is called. I want the player to jump/slide/move lanes instantly or smoothly.
Here is the code
private void FixedUpdate() {
if (!isRunning)
return;
if ((Time.time - _speedIncreaseLastTick) > _speedIncreaseTime) {
_speedIncreaseLastTick = Time.time;
_speed += _speedIncreaseAmount;
}
if(InputManager.Instance.SwipeLeft)
{
_MoveLane(false);
}
if (InputManager.Instance.SwipeRight)
{
_MoveLane(true);
}
Vector3 targetPosition = transform.position.z * Vector3.forward;
switch (_desiredLane)
{
case 0:
targetPosition += Vector3.left * LaneDistance;
break;
case 2:
targetPosition += Vector3.right * LaneDistance;
break;
}
Vector3 moveVector = Vector3.zero;
moveVector.x = (targetPosition - transform.position).normalized.x * _speed;
bool isGrounded = _IsGrounded();
_anim.SetBool("Grounded", isGrounded);
if (_IsGrounded()) // is grounded
{
_verticalVelocity = -0.1f;
if (InputManager.Instance.SwipeUp) {
_verticalVelocity = _jumpForce;
_anim.SetTrigger ("Jump");
} else if (InputManager.Instance.SwipeDown) {
StartSliding ();
Invoke(nameof(StopSliding), 1f);
}
}
else
{
_verticalVelocity -= (_gravity * Time.deltaTime);
if (InputManager.Instance.SwipeDown)
{
_verticalVelocity = -_jumpForce;
}
}
moveVector.y = _verticalVelocity;
moveVector.z = _speed;
_controller.Move(moveVector * Time.deltaTime);
Vector3 dir = _controller.velocity;
if (dir != Vector3.zero)
{
dir.y = 0f;
transform.forward = Vector3.Lerp(transform.forward, dir, TURN_SPEED);
}
}
private void StartSliding()
{
_anim.SetBool(Sliding, true);
_controller.height /= 2;
var center = _controller.center;
center = new Vector3(center.x, center.y / 2, center.z);
_controller.center = center;
}
private void StopSliding()
{
_anim.SetBool(Sliding, false);
_controller.height *= 2;
var center = _controller.center;
center = new Vector3(center.x, center.y * 2, center.z);
_controller.center = center;
}
private void _MoveLane(bool goingRight)
{
_desiredLane += (goingRight) ? 1 : -1;
_desiredLane = Mathf.Clamp(_desiredLane, 0, 2);
}
private bool _IsGrounded()
{
var bounds = _controller.bounds;
var groundRay = new Ray(
new Vector3(
bounds.center.x,
bounds.center.y - bounds.extents.y + 0.2f,
bounds.center.z),
Vector3.down);
Debug.DrawRay(groundRay.origin, groundRay.direction, Color.cyan, 1f);
return Physics.Raycast(groundRay, 0.3f);
}
public void StartRunning()
{
isRunning = true;
_anim.SetTrigger(Running);
}
is this the code related or a setting related problem?
Comment