2017-07-02 45 views
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”方向。

回答

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轴上确定球的一些向上的力。在上面的代码片段中,我将这个设置为0.