【发布时间】:2017-07-25 07:04:04
【问题描述】:
我正在尝试使用字符控制器制作像地铁冲浪者这样的玩家运动控制器,所有的东西都可以用键盘正常工作,但我在滑动时遇到了问题。当我滑动它时,它只移动一帧。而且我希望玩家在空中(跳跃)时左右移动。请帮忙。
这是我的代码:
using UnityEngine;
using System.Collections;
public class PlayerControllerScript : MonoBehaviour
{
public float speed = 8.0F;
public float jumpSpeed = 16.0F;
public float gravity = 80.0F;
private Vector3 moveDirection = Vector3.zero;
public int laneNumber = 1;
public int lanesCount = 3;
bool didChangeLastFrame = false;
public float laneDistance = 2;
public float firstLaneXPos = -2;
public float deadZone = 0.1f;
public float sideSpeed = 12;
private bool Right = false;
private bool Left = false;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
float input = Input.GetAxis("Horizontal");
if (controller.isGrounded) {
if (Mathf.Abs(input) > deadZone)
{
if (!didChangeLastFrame)
{
didChangeLastFrame = true;
laneNumber += Mathf.RoundToInt(Mathf.Sign(input));
if (laneNumber < 0) laneNumber = 0;
else if (laneNumber >= lanesCount) laneNumber = lanesCount - 1;
}
}
else
{
didChangeLastFrame = false;
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump") || SwipeManager.IsSwipingUp())
moveDirection.y = jumpSpeed;
}
}
if (Left)
moveDirection.x = -jumpSpeed;
if (Right)
moveDirection.x = jumpSpeed;
if (SwipeManager.IsSwipingLeft())
{
Left = true;
Right = false;
}
if (SwipeManager.IsSwipingRight())
{
Right = true;
Left = false;
}
Vector3 pos = transform.position;
pos.x = Mathf.Lerp(pos.x, firstLaneXPos + laneDistance * laneNumber, Time.deltaTime * sideSpeed);
transform.position = pos;
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
【问题讨论】:
-
将
CharacterController controller移动到private脚本的private字段以获得更好的性能。因为不变。并在Start()中制作controller = GetComponent<CharacterController>();。 -
是的,你是对的,我把它移到了 Start(),可以帮我解决我问的问题吗? @KamikyIT
标签: unity3d