2017-04-22 8 views
1

別のゲームオブジェクトのアウトラインに沿ってゲームオブジェクトのインスタンスを移動したいと考えています。それはUnityの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とπの間の角度を、負の場合は-πと0の間になるように符号が付けられます。 https://math.stackexchange.com/questions/67026/how-to-use-atan2


ラジアンタンY/Xでの角度を返します。 戻り値は、x軸と0から始まり(x、y)で終了する2Dベクトルの間の角度です。

https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html

Mathf.Rad2Deg:

ラジアンから度変換定数(読み取り専用)。

これは360 /(PI * 2)に等しい。

関連する問題