在Raycast2D上实例化对象命中并旋转实例

时间:2017-04-22 16:05:27

标签: c# unity3d unity5 quaternions unity2d

我想沿着另一个游戏对象的轮廓移动游戏对象的实例。它是Unity的2D项目。

我目前的代码:

Vector3 mousePosition = m_camera.ScreenToWorldPoint(Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast(new Vector2(mousePosition.x, mousePosition.y), new Vector2(player.transform.position.x, player.transform.position.y));
    if (hit.collider != null &&  hit.collider.gameObject.tag == "Player") {
        if (!pointerInstance) {
            pointerInstance = Instantiate(ghostPointer, new Vector3(hit.point.x, hit.point.y, -1.1f), Quaternion.identity);
        } else if(pointerInstance) {
            pointerInstance.gameObject.transform.position = new Vector3(hit.point.x, hit.point.y, -1.1f);
            pointerInstance.gameObject.transform.eulerAngles = new Vector3(0f, 0f, hit.normal.x);
        }

    }

不幸的是,gameObject不会向鼠标旋转,而且有时也会关闭playerObject左侧的位置。我尝试将Instantiate()与Quaternion.LookRotation(hit.normal)一起使用,但也没有运气。

这是我想要实现的草图: instance of tree is shown on the surface of the player facing towards the mousepointer

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

最好使用数学方式而不是物理方式(Raycasting),因为在光线投射中你必须多次投射光线来检查生命值并旋转你的物体,这会让你的游戏产生滞后。

将此脚本附加到您的实例化对象:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
    public Transform Player;

    void Update()
    {
        //Rotating Around Circle(circular movement depend on mouse position)
        Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(Player.position);
        targetScreenPos.z = 0;//filtering target axis
        Vector3 targetToMouseDir = Input.mousePosition - targetScreenPos;

        Vector3 targetToMe = transform.position - Player.position;

        targetToMe.z = 0;//filtering targetToMe axis

        Vector3 newTargetToMe = Vector3.RotateTowards(targetToMe, targetToMouseDir,  /* max radians to turn this frame */ 2, 0);

        transform.position = Player.position +  /*distance from target center to stay at*/newTargetToMe.normalized;


        //Look At Mouse position
        var objectPos = Camera.main.WorldToScreenPoint(transform.position);
        var dir = Input.mousePosition - objectPos;
        transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg);

    }
}

有用的解释

ATAN2:

  

atan2(y,x)给出x轴和矢量(x,y)之间的角度,通常以弧度为单位并且有符号,使得对于正y,您获得0和π之间的角度,并且对于负y结果在-π和0之间。   https://math.stackexchange.com/questions/67026/how-to-use-atan2

           

以Tan为y / x的弧度返回角度。   返回值是x轴和2D矢量之间的角度,从零开始并终止于(x,y)。   https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html

Mathf.Rad2Deg:

  

Radians-to-degrees转换常数(只读)。

     

这等于360 /(PI * 2)。