从相机的POV射击球

时间:2018-10-26 02:28:01

标签: c# unity3d camera transform

我知道这个问题已经被问过几次了,但是我相信我的问题可以解决而不会太麻烦(希望!),并且有点独特。我正在编写一个迷你高尔夫球脚本来射击球,目的是远离摄像机的POV射击。但是我无法做到这一点。我确定它与camera.transform有关,但不确定。我对在Unity中进行编码完全不了解。我只需要一种简单明了的方法就可以使此悬挂的高尔夫球沿相机面向的任何方向直线移动。请帮忙!

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitBall2 : MonoBehaviour
{

    Rigidbody rigidBody;
    bool StartedShot;
    Vector3 shotStart;
    Vector3 shotEnd;
    Vector3 direction;
    public float distance;
    public float forceAdjust = 0.05f;

    void Start()
    {

        rigidBody = this.GetComponent<Rigidbody>();
        StartedShot = false;
    }


    void Update()
    {
        if (Input.GetMouseButtonUp(1))
        {
            rigidBody.velocity = Vector3.zero;
            this.transform.position = Vector3.zero;
            StartedShot = false;
        }

        // Starting shot
        if (!StartedShot && Input.GetMouseButtonDown(0))
        {
            StartedShot = true;
            shotStart = Input.mousePosition;
        }

        // Ending shot
        if (StartedShot && Input.GetMouseButtonUp(0))
        {
            shotEnd = Input.mousePosition;
            direction =  Camera.main.transform.forward - shotEnd;
            float distance = direction.magnitude;
            StartedShot = false;

            Vector3 shootDirection = new Vector3(direction.x, 0.0f, direction.y);

            rigidBody.AddForce(shootDirection * rigidBody.mass * forceAdjust, ForceMode.Impulse);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如上面的评论所述,要向前射击,只需使用camera transform.forward

答案 1 :(得分:0)

好吧,我如下更改了脚本,球现在从相机移开了。球的速度和它的y轴跳动有一点问题,但是我敢肯定它很容易弄清楚。

更改了“ Vector3 ShootDirection =新的Vector3(direction.x,0.0f,direction.y);”

到Vector3 ShootDirection = Camera.main.transform.forward;

谢谢大家!