AddForce在第一人称视图方向3d

时间:2017-07-02 16:33:09

标签: c# unity3d

假设我有两个对象:

  • 对象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”方向前进。

1 个答案:

答案 0 :(得分:0)

要获得所需的效果,您还必须在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轴上将施加力。您还必须确定y轴上球的一些向上力。在上面的代码片段中,我将其设置为0。