2017-04-22 6 views
1

다른 게임 개체의 윤곽을 따라 gameObject의 인스턴스를 이동하려고합니다. 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의 왼쪽에있는 위치를 향해 회전하지 않는 때로는 오프에 있습니다. Instantiate()를 Quaternion.LookRotation (hit.normal)과 함께 사용하려했지만 행운이 없었습니다. 여기

내가 무엇을 달성하고자하는의 거친 스케치

는 : instance of tree is shown on the surface of the player facing towards the mousepointer

어떤 도움에 감사드립니다. 감사!

답변

1

raycasting에서 광선을 던져서 체력을 확인하고 개체를 회전해야하기 때문에 물리 방식 (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


라디안 황갈색 Y/(X)을 각도를 돌려. 반환 값은 x 축과 0에서 시작하여 (x, y)에서 끝나는 2D 벡터 간의 각도입니다. https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html

Mathf.Rad2Deg :

라디안 - 투 -도 ​​변환 상수 (읽기 전용).

이것은 360/(PI * 2)와 같습니다.