球在unity3d中没有被正确的方向抛出?

时间:2017-07-13 06:45:21

标签: unity3d

我正在制作一个玩家在3D视图中投掷篮球的游戏,但它可能无法正常投掷。当玩家将鼠标向上移动时,我需要在z方向上正确地投掷球。

游戏的参考链接我想要的东西:

参考链接1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; 
using UnityEngine.SceneManagement;

public class BallController : MonoBehaviour
{

public static BallController instance;

[SerializeField]
private GameObject Player;

private Vector3 touchStart;

private Vector3 touchEnd;

private Vector3 screenPoint;

private Vector3 offset;

void OnMouseUp ()
{
    ThrowBall ();
}
public void ThrowBall ()
{
        touched = true;
        Vector3 pos1 = new Vector3 ();
        Vector3 pos2 = new Vector3 ();
        touchStart.z = Camera.main.nearClipPlane - (.2f);
        touchEnd.z = Camera.main.nearClipPlane - (0.08f);

        pos1 = Camera.main.ScreenToWorldPoint (touchStart);
        pos2 = Camera.main.ScreenToWorldPoint (touchEnd);

        Vector3 v = pos2 - pos1; 
        v.z = 0.02f;

        Player.GetComponent<Rigidbody> ().AddForce (v * 600, ForceMode.Impulse);
  }
}

1 个答案:

答案 0 :(得分:0)

使用transform.forward获取本地z轴:

Vector3 v = pos2 - pos1; 
        v.z = 0.02f * transform.forward;
 Player.GetComponent<Rigidbody> ().AddForce (v * 600, ForceMode.Impulse);

或者您可以使用

v.z = 0.02f;
 Player.GetComponent<Rigidbody> ().AddForce (v * 600 * transform.forward, ForceMode.Impulse);