繁体   English   中英

在第一人称视角3d方向上的AddForce

[英]AddForce in First Person view direction 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”方向移动。

为了获得理想的效果,您还必须在x方向上施加一些力。 这可以通过更改将力施加到类似

Vector3 direction = new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle));
Vector3 force = direction * forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax);
GetComponent<Rigidbody>().AddForce(force, ForceMode.VelocityChange);

这样,您的角度将是围绕y轴的旋转,您将在其中施加力。 您还必须确定球在y轴上的一些向上力。 在上面的代码片段中,我将其设置为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM