【问题标题】:How can I launch the ball based on the position of the touch on the screen?如何根据屏幕上的触摸位置发射球?
【发布时间】:2018-11-30 15:49:09
【问题描述】:

所以我正在尝试制作一个游戏,要求你设置一个必须在特定平台上反弹才能到达目的地的球的角度和速度。

现在,我如何找到从手指接触到球的方向,以使其“远离手指”移动。

我尝试使用向量的减法来获得方向,但它不起作用,因为向量是相对于世界原点的......它总是给我一个错误的方向......

我该如何解决这个问题,我需要一个相对于触摸和玩家(球)而不是世界的方向矢量,这样我才能发射球。

你会看到,在下一张图片中,我正在用鼠标箭头模拟触摸(假设鼠标箭头是玩家的手指。我想根据手指相对于的距离和位置来发射球球。它在代码中效果很好,但只有当球被放置在场景的原点时,所以我认为这是一个向量的数学问题,我不知道如何解决......

下面是我现在拥有的代码。它附加到球的游戏对象:

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

public class PlayerController : MonoBehaviour {

    [SerializeField]
    Camera playerCamera;
    Rigidbody rb;
    Vector3 touchPostion;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }
    private void FixedUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            LounchPlayer();
        }
    }

    void LounchPlayer()
    {
        Vector2 mousePos = Input.mousePosition;
        touchPostion = (transform.position - playerCamera.ScreenToWorldPoint(
                                            new Vector3(mousePos.x, 
                                                       mousePos.y, 
                                                       playerCamera.transform.position.z))).normalized;
        rb.AddForce(touchPostion.normalized, ForceMode.Impulse);
    }
}

【问题讨论】:

  • 球不应该有它自己的Vector吗?这样您就可以判断球相对于World Vector 的移动方向?那么你可以计算出玩家VectorWorld Vector之间的方向,然后让球朝着那个计算出的方向移动?
  • 什么意思?我只需要一个矢量方向,所以我可以使用 rb.AddForce() 函数...
  • 如果你得到了与鼠标箭头和世界相关的Vector,那不也是玩家应该进入的Vector吗?

标签: c# unity3d


【解决方案1】:

在找到你的触摸位置时,ScreenToWorldPoint 参数的 z 分量应该是沿着相机前向矢量的适当距离,绝对不是相机的世界 z 位置。 playerCamera.nearClipPlane 在这里很合适,但实际上任何小的常量(例如0)就足够了。

另外,发射方向也不需要两次归一化。

Vector2 mousePos = Input.mousePosition;
touchPostion = (transform.position - playerCamera.ScreenToWorldPoint(
        new Vector3(
            mousePos.x, 
            mousePos.y, 
            playerCamera.nearClipPlane))
        ).normalized;  // This isn't a position vector; it's a direction vector. 
                       // The var name "touchPosition" is misleading and should be changed.

float launchMagnitude = 1f; // change this to adjust the power of the launch

rb.AddForce(touchPostion * launchMagnitude , ForceMode.Impulse);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2010-11-13
    • 2011-05-23
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多