【发布时间】:2016-12-23 22:06:08
【问题描述】:
我正在尝试将跳转添加到我们的控制脚本的控件中,但它还不能正常工作,而且我有点沮丧,因为我尝试了很多让它工作。我不使用刚体,而是想使用基于脚本的物理和 - 但后来 - 射线投射(检测地面)。它是 3D 但具有固定视角,因为角色是精灵(我们正在考虑尝试类似于饥荒、纸片马里奥等的风格)。我现在要添加的内容是在角色静止不动时向上跳跃,然后在跳跃时让角色在角色移动时移动一段距离。好吧,你明白了。为此,我首先需要完全开始跳跃工作 - 还要考虑重力将角色放回原位,同时还要考虑角色可能降落在与起始地面不同高度的地面上。 现在发生的情况是,角色只跳了一点点,就像连一跳都没有,然后无休止地跌倒——或者当再次按下跳跃时,无休止地上升。那么,我该如何解决呢?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controls3D : MonoBehaviour
{
public float player3DSpeed = 5f;
private bool IsGrounded = true;
private const float groundY = (float) 0.4;
private Vector3 Velocity = Vector3.zero;
public Vector3 gravity = new Vector3(0, -10, 0);
void Start()
{
}
void Update()
{
if (IsGrounded)
{
if (Input.GetButtonDown("Jump"))
{
IsGrounded = false;
Velocity = new Vector3(Input.GetAxis("Horizontal"), 20, Input.GetAxis("Vertical"));
}
Velocity.x = Input.GetAxis("Horizontal");
Velocity.z = Input.GetAxis("Vertical");
if (Velocity.sqrMagnitude > 1)
Velocity.Normalize();
transform.position += Velocity * player3DSpeed * Time.deltaTime;
}
else
{
Velocity += gravity * Time.deltaTime;
Vector3 position = transform.position + Velocity * Time.deltaTime;
if (position.y < groundY)
{
position.y = groundY;
IsGrounded = true;
}
transform.position = position;
}
}
}
【问题讨论】:
-
无休止的摔倒问题解决了。只需设置 Velocity.y = 0;在 transform.position = 位置之后;在 IsGrounded = true;
-
如果你一步一步来,我打赌你会看到初始速度比你想象的要小,因为
Velocity.Normalize();,所以你的 Velocity.y 是介于 -1 和 1 之间的某个数字。我认为你的向上速度应该独立于其他两个方向,或者,您可能应该在每次修改它时标准化速度,而不是仅在接地时。即,为什么在接地情况下进行规范化而不是在这里:Velocity += gravity * Time.deltaTime;? -
我想我现在得到了一些东西,谢谢。