c# - 为什么我的代码不能在 Unity 中运行?统一 C#
问题描述
出于某种原因,我的代码无法正常工作......我不知道为什么。有人可以帮忙吗?我正在使用 switch 语句来控制我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 pos = transform.position;
string state = "idle";
float vx = 0f;
float vy = 0f;
float playerSpeed = 2f * Time.deltaTime;
switch (state) {
case "idle":
vx = 0;
vy = 0;
if (Input.GetKey (KeyCode.A)) state = "left";
if (Input.GetKey (KeyCode.D)) state = "right";
if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";
break;
case "left":
vx = -1 * playerSpeed;
vy = 0;
if (Input.GetKey (KeyCode.A)) state = "left";
if (Input.GetKey (KeyCode.D)) state = "right";
if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";
break;
case "right":
vx = playerSpeed;
vy = 0;
if (Input.GetKey (KeyCode.A)) state = "left";
if (Input.GetKey (KeyCode.D)) state = "right";
if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";
break;
}
vx += pos.x;
vy += pos.y;
pos += transform.position;
}
}
控制台没有错误,我的代码看不到任何错误......
请帮忙!
非常感谢任何答案。
谢谢。
解决方案
您正在评估每个 switch 案例中的输入,而不是在评估 switch 之前。您还在检查输入,然后检查是否缺少输入,因此只需用于else
清理这些检查。你也什么都不做,vy = 0
所以不要费心设置:
if (Input.GetKey (KeyCode.A))
state = "left";
else if (Input.GetKey (KeyCode.D)) // if you hold both A and D, A will get priority
state = "right";
else
state = "idle";
switch(state)
{
case("idle")
vx = 0;
break;
case("left")
vx = playerSpeed;
break;
case("right")
vx = -1 * playerSpeed;
break;
}
您也没有正确地将值添加到转换的位置,您只是将它们添加到您的临时变量中,pos
(您根本不需要的变量):
vx += pos.x;
vy += pos.y;
pos += transform.position;
应该改为:
transform.position.Translate(vx, vy, 0);
我还想指出,开关本身完全没有意义,但我把这个作为我的答案,所以很清楚做错了什么;你应该只是在 // 语句中设置你的vx
值。if
else if
else
推荐阅读
- macos - 意外的头文件:
- windbg - 什么在 .net 应用程序中使用大型 mem_reserve?
- django - django 中的自定义身份验证不起作用
- android - 日期选择器 - 更改所选日期 Android
- node.js - 当代码在本地运行时,为什么在 heroku 中使用 node.js 会给我不同的结果?
- php - 为什么不能将字符串转换为数字
- python - 如何对“groupby”执行操作,例如美元重量等
- c# - Xamarin 表单中的 System.Net.WebExceptionStatus 异常
- c# - 如何在一个 Outlook VSTO 中使用多个 XML 功能区
- localhost - 管道编辑器中的可见元素