2017-04-22 132 views
1

我想沿着另一个gameobject的轮廓移动一个gameObject的实例。它是一个统一的2D项目。Raycast2D实例化对象命中并旋转实例

我当前的代码:

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); 
     } 

    } 

不幸的是,游戏对象不会对鼠标的playerObject左侧的位置旋转有时也被关闭。我试图用Quaternion.LookRotation(hit.normal)使用Instantiate(),但也没有运气。

这里是我想达到的草图: instance of tree is shown on the surface of the player facing towards the mousepointer

任何帮助表示赞赏。谢谢!

回答

1

最好使用数学方法而不是物理方式(光线投射),因为在光线投射中,您必须多次投射光线来检查命中点并旋转对象,这会使游戏滞后。

安装这个脚本到您的实例化对象:

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


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

Mathf.Rad2Deg:

弧度到度的转换常数(只读)。

这等于360 /(PI * 2)。