在C#(Unity引擎)中混淆矢量
本文关键字:Unity 引擎 | 更新日期: 2023-09-27 18:27:03
我是Unity中C#编程的新手,在z轴上移动时会遇到一些问题。问题是,当我松开向上按钮时,我会继续移动。然而,当我在x轴上移动时,这很好,因为松开按钮会停止玩家。代码如下:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public Vector3 motion = new Vector3();
private CharacterController controller;
private bool onGround;
private float xRot, yRot;
public static float X_ROTATION = 0;
public static float Y_ROTATION = 0;
private const float lookSpeed = 2.0f;
public void Start() {
controller = GetComponent<CharacterController>();
}
public void FixedUpdate() {
if(Screen.lockCursor) {
Vector3 impulse = new Vector3();
if(Input.GetKey(KeyCode.W)) impulse.z+=1;
if(Input.GetKey(KeyCode.A)) impulse.x-=1;
if(Input.GetKey(KeyCode.S)) impulse.z-=1;
if(Input.GetKey(KeyCode.D)) impulse.x+=1;
if(impulse.sqrMagnitude > 0) {
motion += Quaternion.Euler(new Vector3(0, xRot, 0)) * impulse.normalized * 0.05f;
}
if(onGround) {
if(Input.GetKey(KeyCode.Space)) {
motion.y += 0.2f;
}
}
motion.y -= 0.015f;
Vector3 oldMotion = motion;
Vector3 oldPos = controller.transform.localPosition;
controller.Move(motion);
Vector3 newPos = controller.transform.localPosition;
motion = newPos - oldPos;
onGround = oldMotion.y < -0.0001f && motion.y >= -0.0001f;
motion.x *= 0.8f;
motion.y *= 0.8f;
}
}
public void Update() {
if(Screen.lockCursor && Input.GetKeyDown(KeyCode.Escape)) {
Screen.lockCursor = false;
}
if(!Screen.lockCursor && Input.GetMouseButtonDown(0)) {
Screen.lockCursor = true;
}
if(Screen.lockCursor) {
xRot += Input.GetAxis("Mouse X") * lookSpeed;
yRot -= Input.GetAxis("Mouse Y") * lookSpeed;
if(yRot < -90) yRot = -90;
if(yRot > 90) yRot = 90;
if(xRot < -180) xRot += 360;
if(xRot >= 180) xRot -= 360;
controller.transform.localRotation = Quaternion.Euler(new Vector3(yRot, xRot, 0));
}
Player.X_ROTATION = xRot;
}
}
FixedUpdate()中最后几个您已经编码的语句-
motion.x *= 0.8f;
motion.y *= 0.8f;
还应包含
motion.z *= 0.8f;
可能是你不需要的-
motion.y *= 0.8f;
正如Gkills所说,您应该在最后为motion.z
修复motion.y
的"耗尽"。
此外,您可能需要交换
motion += Quaternion.Euler(new Vector3(0, xRot, 0)) * impulse.normalized * 0.05f;
对于
motion += transform.rotation * impulse.normalized * 0.05f;
然后将脉冲y分量归零,以防止玩家飞行。
最后,您可能希望在更新中使用Time.deltaTime
(因此鼠标外观与帧速率无关)