参考官方:https://unity3d.com/cn/learn/tutorials/modules/beginner/live-training-archive/hover-car-physics?playlist=17120
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class HoverMotor : MonoBehaviour
{
public float speed = 90f; //移动速度
public float turnSpeed = 5f; //旋转速度
public float hoverForce = 65f; //悬浮力
public float hoverHeight = 3.5f;//悬浮高度
private float powerInput;
private float turnInput;
private Rigidbody carRigidbody;
void Awake()
{
carRigidbody = GetComponent<Rigidbody>();
}
void Update()
{
powerInput = Input.GetAxis("Vertical");
turnInput = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, hoverHeight))
{
float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverForce;
carRigidbody.AddForce(appliedHoverForce, ForceMode.Acceleration);
}
carRigidbody.AddRelativeForce(0f, 0f, powerInput * speed);
carRigidbody.AddRelativeTorque(0f, turnInput * turnSpeed, 0f);
}
}
网友评论