首页 > 解决方案 > 统一切换车道后人物一直在波动?

问题描述

我正在开发像地铁冲浪者这样的游戏,但是在编写车道切换脚本后,一旦我切换车道,我的角色就​​会开始波动。我已经用谷歌搜索了这个问题并尝试了多种解决方案,但都是徒劳的。我究竟做错了什么?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;

public class PlayerMotor : MonoBehaviour {

    private const float LANE_DISTANCE = 3.0f;
    private const float TURN_SPEED = 0.05f;
    private int desiredLane = 1; // 0 is left 1 is middle and 2 is right
    private float gravity = 12.0f;
    //vertical velocity 0.0
    private float verticalVelocity;
    private Vector3 moveVector;


    private bool isRunning = false;
    private Animator anim;
    private float jumpForce = 6.0f;
    private CharacterController controller;


    private float animationDuration = 3.0f;
    private float startTime;
    private bool isDead = false;


    //Speed Modifier
    private float orignalSpeed = 8.0f;
    private float speed;
    private float speedIncreasLastTick;
    private float speedIncreaseTime = 2.5f;
    private float speedIncreaseAmount = 0.8f;


    //sounds
    public AudioClip slide;
    public AudioClip collide;
    //public AudioClip StartMenu;
    //public AudioClip RunningSound;

    void Start () {

        speed = orignalSpeed;
        controller = GetComponent<CharacterController> ();
        startTime = Time.time;

    }


    void Update () {


        if(Time.time - speedIncreasLastTick > speedIncreaseTime)
        {
            speedIncreasLastTick = Time.time;
            speed += speedIncreaseAmount;

        }

        if (Input.GetKeyDown(KeyCode.LeftArrow))
            MoveLane (false);
        if (Input.GetKeyDown(KeyCode.RightArrow))
            MoveLane (true);

        Vector3 targetPosition = transform.position.z * Vector3.forward;
        if (desiredLane == 0)
            targetPosition += Vector3.left * LANE_DISTANCE;
        else if (desiredLane == 2)
            targetPosition += Vector3.right * LANE_DISTANCE;

        Vector3 moveVector = Vector3.zero;
        moveVector.x = (targetPosition - transform.position).normalized.x * speed;





        moveVector.y = verticalVelocity;
        moveVector.z = speed;


        //Move charachter

        controller.Move(moveVector * Time.deltaTime);

        //Rotate the character
        Vector3 dir = controller.velocity;
        if (dir != Vector3.zero) {
            dir.y = 0;
            transform.forward = Vector3.Lerp (transform.forward, dir, TURN_SPEED);
        }


    }

    public void SetSpeed(float modifier)
    {
        speed = 5.0f + modifier;
    }




    private void MoveLane(bool goingRight)
    {
        desiredLane += (goingRight) ? 1 : -1;
        desiredLane = Mathf.Clamp (desiredLane, 0, 2);
    }

}

角色的 position.x 和旋转应该为零,但在切换车道后它开始波动

在此处输入图像描述

标签: unity3dgame-physics

解决方案


推荐阅读