我需要你的帮助。 我制作了一个 Hover-car movement 脚本。 距离地面和悬停运动的距离由 Raycast 计算, 我做了另一个Raycast ,因为有一个问题 - 如果按住按钮,悬停飞得太高。 但是现在有两个Raycast会导致延迟 - 悬停会突然移动。 插值无济于事。
如何在没有抽搐的情况下轻松移动? 请帮忙。
public class hoverController_v7 : MonoBehaviour
Rigidbody carBody;
float deadZone = 0.1f;
public float hoverForce = 9.0f;
public float hoverHeight = 2.0f;
public GameObject[] hoverPoints;
public float forwardAcceleration = 100.0f;
public float backwardAcceleration = 25.0f;
public float currThrust = 0.0f;
public float turnStrength = 10.0f;
public float currTurn = 0.0f;
public GameObject leftAirBrake;
public GameObject rightAirBrake;
int layerMask;
void Start()
{
carBody = GetComponent<Rigidbody>();
layerMask = 1 << LayerMask.NameToLayer("Characters");
layerMask = ~layerMask;
}
void OnDrawGizmos()
{
// сила hoverForce
RaycastHit hit;
for(int i = 0; i < hoverPoints.Length; i++)
{
var hoverPoint = hoverPoints[i];
if(Physics.Raycast(hoverPoint.transform.position,
-Vector3.up, out hit,
hoverHeight,
layerMask))
{
Gizmos.color = Color.yellow;
//Color if correctly alligned
Gizmos.DrawLine(hoverPoint.transform.position, hit.point);
Gizmos.DrawSphere(hit.point, 0.5f);
}
else
{
Gizmos.color = Color.red;
//Color if incorrectly alligned
Gizmos.DrawLine (hoverPoint.transform.position, hoverPoint.transform.position - Vector3.up * hoverHeight);
}
}
}
void Update()
{
// main thrust
currThrust = 0.0f;
float aclAxis = Input.GetAxis("Vertical");
if(aclAxis > deadZone)
{
currThrust = aclAxis * forwardAcceleration;
}
else if(aclAxis < -deadZone)
{
currThrust = aclAxis * backwardAcceleration;
}
// Turning
currTurn = 0.0f;
float turnAxis = Input.GetAxis("Mouse X") * 2;
if(Mathf.Abs(turnAxis) > deadZone)
currTurn = turnAxis;
}
void FixedUpdate()
{
// hover force
RaycastHit hit;
for(int i = 0; i < hoverPoints.Length; i++)
{
var hoverPoint = hoverPoints[i];
if(Physics.Raycast(hoverPoint.transform.position,
-Vector3.up, out hit,
hoverHeight, layerMask))
carBody.AddForceAtPosition(Vector3.up * hoverForce * (1.0f -(hit.distance / hoverHeight)),
hoverPoint.transform.position);
else
{
if(transform.position.y > hoverPoint.transform.position.y)
carBody.AddForceAtPosition(hoverPoint.transform.up * hoverForce, hoverPoint.transform.position);
else
//add force to car
carBody.AddForceAtPosition(hoverPoint.transform.up * -hoverForce, hoverPoint.transform.position);
}
}
// forward
RaycastHit hit2;
if(Physics.Raycast(transform.position, -transform.up, out hit2))
{
if(hit2.distance < 2)
{
if(Mathf.Abs(currThrust) > 0)
{
carBody.AddForce(transform.forward * currThrust);
}
}
}
// turn
if(currTurn > 0)
{
carBody.AddRelativeTorque(Vector3.up * currTurn * turnStrength);
}
else if(currTurn < 0)
{
carBody.AddRelativeTorque(Vector3.up * currTurn * turnStrength);
}
}
}
答案 0 :(得分:0)
您需要重新考虑游戏的逻辑。 Raycast的计算成本很高。你在FixedUpdate()
开了两枪。然后你在更新中有一个for循环,这通常是一个坏主意。
如果你真的需要知道到地面的距离,请在Update()
上发射光线投射。