【发布时间】:2020-04-28 19:48:36
【问题描述】:
朋友们,新开发者问,我浏览了很多网站并尝试了很多不同的脚本,将脚本与玩家移动和其他脚本分开,但无济于事,并提出了这个作为我所见但它的集合体也根本不起作用。我在 subreddits 或这个中找不到任何东西。我知道我的正常运动代码可能很难看,但它可以工作。希望你能帮忙谢谢!
为了澄清这是让玩家在按住 shift 键的同时冲刺,感谢那些提醒我详细说明的人。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(UnityEngine.AI.NavMeshAgent))]
public class PlayerMovement : MonoBehaviour
{
UnityEngine.AI.NavMeshAgent agent;
private Rigidbody rb;
public float movementSpeed = 5.0f;
public float clockwise = 1000.0f;
public float counterClockwise = -5.0f;
public float Speed = 5.0f;
public Vector3 jump;
public float jumpForce =1.0f;
public float shiftSpeed = 10.0f;
public bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 1.0f, 0.0f);
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void OnCollisionStay()
{
isGrounded = true;
}
void Update()
{
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
transform.position += transform.forward \* Time.deltaTime \* movementSpeed;
}
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftShift))
{
transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
}
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
transform.position -= transform.forward \* Time.deltaTime \* movementSpeed;
}
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow) && Input.GetKey(KeyCode.LeftShift))
{
transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
}
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
GetComponent<Rigidbody>().position += Vector3.left \* Time.deltaTime \* movementSpeed;
}
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.LeftShift))
{
transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
}
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
GetComponent<Rigidbody>().position += Vector3.right \* Time.deltaTime \* movementSpeed;
}
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.LeftShift))
{
transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump \* jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
}
【问题讨论】:
-
在本文正文中详细说明您的问题可能是个好主意。
-
小心
&&和||,您可能需要考虑在||部分周围使用一些括号( ),否则它可能会被解释为if(Input.GetKey(KeyCode.D) || (Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.LeftShift))),因此只需转换为备用键 -
另请注意:当涉及
Rigidbody时,不要不要使用transform.position = ......这会破坏物理...而不是使用GetComponent<Rigidbody>().MovePosition(...);或直接设置GetComponent<Rigidbody>().velocity = ...; -
涉及如此多的轴和方向,再加上布尔逻辑,很难理解。如果你能展示一个最小的例子,比如说,只有一个轴,那就太好了。
标签: unity3d