基于鼠标瞄准Unity3d [英] Mouse based aiming Unity3d

查看:799
本文介绍了基于鼠标瞄准Unity3d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在炮弹射击游戏。这里有一个简短的代码,我在哪里计算瞄准方向

I am making cannonball shooter game. here's a short code where I am calculating the aiming direction.

            Vector3 mousePos = Input.mousePosition;
            mousePos.z = thisTransform.position.z - camTransform.position.z;
            mousePos = mainCamera.ScreenToWorldPoint (mousePos);

            Vector3 force = mousePos - thisTransform.position;
            force.z = force.magnitude;

这工作当两个球,在角度(0,0,0)。但是,当角度的变化,我不能够在正确的方向进行拍摄。

This works when both ball and at angle (0,0,0). But when the angle changes, I am not able to shoot at right direction.

假设两个球和相机正在寻找在右侧45度,同样的代码没有按'将不起作用。

Suppose both ball and camera are looking at 45 degrees on right side, the same code doesn't work.

目前的代码假定他们都处于角度(0,0,0)。因此,在上述情况下,投掷方向永远是错的。

The current code assumes both are at angle (0,0,0). So in the above mentioned case, the throwing direction is always wrong.

我要扔在它是任何方向的球。但是,假设它为0角度,并相应地抛出。

I want to throw the ball in whatever direction it is. But assume it as 0 angle and throw accordingly.

推荐答案

使用 Camera.ScreenToWorldPoint 是错在这种情况下。

Using Camera.ScreenToWorldPoint is wrong in this situation.

您应该使用光线投射对一个平面。这里是没有unnecesary数学示范:

You should be using raycasting against a plane. Here's a demonstration without unnecesary math:

光线投射给你的优势,你不必去猜测如何深做了用户点击(在ž 坐标)

Raycasting gives you the advantage, that you don't have to guess how "deep" did the user click (the z coordinate).

下面是一个简单的实现上述的:

Here's a simple implementation of the above:

/// <summary>
/// Gets the 3D position of where the mouse cursor is pointing on a 3D plane that is
/// on the axis of front/back and up/down of this transform.
/// Throws an UnityException when the mouse is not pointing towards the plane.
/// </summary>
/// <returns>The 3d mouse position</returns>
Vector3 GetMousePositionInPlaneOfLauncher () {
    Plane p = new Plane(transform.right, transform.position);
    Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
    float d;
    if(p.Raycast(r, out d)) {
        Vector3 v = r.GetPoint(d);
        return v;
    }

    throw new UnityException("Mouse position ray not intersecting launcher plane");
}






示范开始:的 https://github.com/chanibal/Very-Generic-Missle-Command

这篇关于基于鼠标瞄准Unity3d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆