0
比方说,我有对象:AddForce的第一人称视向3D
- 对象A:球员(第一人称)
- 对象B:球(足球为例)
我想热门球在我看的方向,并给它逼真的物理,就像它会在现实生活中。
这是我走到这一步,(这是或多或少只是用于测试,这就是为什么代码看起来如此的混乱):
using UnityEngine;
using System.Collections;
public class KickScript : MonoBehaviour
{
public float bounceFactor = 0.9f; // Determines how the ball will be bouncing after landing. The value is [0..1]
public float forceFactor = 10f;
public float tMax = 5f; // Pressing time upper limit
private float kickForce; // Keeps time interval between button press and release
private Vector3 prevVelocity; // Keeps rigidbody velocity, calculated in FixedUpdate()
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
kickForce = Time.time;
}
}
}
void FixedUpdate()
{
if (kickForce != 0)
{
float angle = Random.Range(0, 20) * Mathf.Deg2Rad;
GetComponent<Rigidbody>().AddForce(new Vector3(0.0f, forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Sin(angle), forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Cos(angle)), ForceMode.VelocityChange);
kickForce = 0;
}
prevVelocity = GetComponent<Rigidbody>().velocity;
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Ground") // Do not forget assign tag to the field
{
GetComponent<Rigidbody>().velocity = new Vector3(prevVelocity.x, -prevVelocity.y * Mathf.Clamp01(bounceFactor), prevVelocity.z);
}
}
}
出于某种原因,那就只在“Z”方向。