【问题标题】:Unity Shoot Ball From POV of CameraUnity 从摄像机的 POV 拍摄球
【发布时间】:2018-10-26 02:28:00
【问题描述】:

我知道这个问题已经被问过几次了,但我相信我的问题可以在没有太多麻烦的情况下得到解决(希望如此!)并且有点独特。我正在编写一个射击球的迷你高尔夫脚本,旨在远离相机的 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);
        }
    }
}

【问题讨论】:

  • Camera.main.transform.forward?
  • direction = Camera.main.transform.forward; 而不是 direction = Camera.main.transform.forward - shotEnd;
  • 有什么问题?球会射门吗?它会向后射击吗?
  • @CaTs,它垂直于相机向左(在 x 轴上)拍摄,它不会远离相机拍摄。
  • 我已经尝试过 Camera.main.transform.forward,但它并没有像我希望的那样工作。我认为我的问题可能出在“Vector3 shootDirection = new Vector3(direction.x...)。我正在从其他人那里剪下这段代码(谢谢!),但经验不足,无法按照我需要的方式进行编辑。

标签: c# unity3d camera transform


【解决方案1】:

如上面的 cmets 所述,向前拍摄只需使用相机 transform.forward

【讨论】:

    【解决方案2】:

    好的,我按如下方式更改了脚本,球现在远离相机。球的速度和它的 y 轴跳跃有点小问题,但我相信它很容易弄清楚。

    更改了“Vector3 shootDirection = new Vector3(direction.x, 0.0f, direction.y);”

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

    谢谢大家!

    【讨论】:

      猜你喜欢
      • 2011-07-15
      • 2020-07-06
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 2013-03-20
      相关资源
      最近更新 更多