2016-11-04 3 views
0

유니티에서 3D 게임을 만들고 있는데, 플레이어가 마우스를 둘러 볼 수있게 해주는 스크립트가 있습니다. 찾고있는 방향으로 플레이어를 움직이려면 transform.forward를 사용하고 있습니다. 내 문제는 그들이 천장을보고 'W'(앞으로)를 누르면 대기로 상승하기 시작한다는 것입니다. 기본적으로 x 축과 z 축에서만 이동을 허용하는 transform.forward의 메서드 또는 하위 메서드가 있는지 알아야합니다.유니티에서 Y 축 움직임 방지하기`transform.forward`

if (transform.rotation.x < -10) 
     { 
      //do no forward or backward movement 
      Debug.Log("Rotation too great to forward move..."); 
      tooGoodForMovement = true; 

     } 
     else 
     { 
      tooGoodForMovement = false; 
      if (Input.GetKey(KeyCode.W)) 
      { 
       //Forward 
       player.velocity = (transform.FindChild("Main Camera").transform.forward * moveSpeed); 
      } 
      if (Input.GetKey(KeyCode.S)) 
      { 
       //Back 
       player.velocity = (-transform.FindChild("Main Camera").transform.forward * moveSpeed); 
      } 
     } 
     if (Input.GetKey(KeyCode.A)) 
     { 
      //Left 
      player.velocity = -transform.FindChild("Main Camera").transform.right * moveSpeed; 
     } 

     if (Input.GetKey(KeyCode.D)) 
     { 
      //Right 
      player.velocity = transform.FindChild("Main Camera").transform.right * moveSpeed; 
     } 

답변

2

이 임시 변수로 속도 벡터를 설정하고 제로로 Y를 재설정 해보십시오 :

여기 내 이동 스크립트 (C 번호)입니다. 다른 기능에서 다음

Transform camera; 

void Start() 
{ 
    //Cache transform.FindChild so that we don't have to do it every time 
    camera = transform.FindChild("Main Camera"); 
} 

는 :

Vector3 velocity = Vector3.zero; 

if (transform.rotation.x < -10) 
{ 
    //do no forward or backward movement 
    Debug.Log("Rotation too great to forward move..."); 
    tooGoodForMovement = true; 
} 
else 
{ 
    tooGoodForMovement = false; 
    if (Input.GetKey(KeyCode.W)) 
    { 
     //Forward 
     velocity = camera.forward * moveSpeed; 
    } 
    if (Input.GetKey(KeyCode.S)) 
    { 
     //Back 
     velocity = -camera.forward * moveSpeed; 
    } 
} 
if (Input.GetKey(KeyCode.A)) 
{ 
    //Left 
    velocity = -camera.right * moveSpeed; 
} 

if (Input.GetKey(KeyCode.D)) 
{ 
    //Right 
    velocity = camera.right * moveSpeed; 
} 

velocity.Y = 0; 
player.velocity = velocity; 
+1

이 괜찮습니다. 매번 수행 된'FindChild ("Main Camera")'에 대한 수정 사항을 추가하십시오. 그것을 잡는 것이 좋을 것입니다. – Programmer

+0

이것은 효과가 있습니다. 고맙습니다! 나는 그것을 더 일찍 생각해야했다. 또한 @Programmer,'FindChild ("Main Camera")'를 수정하면 무엇을 의미합니까? –

+0

@ Sub6Resources 업데이트 된 답변을 확인하십시오. 'FindChild'를 항상 사용하는 것은 값이 비쌉니다. 변환을 캐시하십시오. – Programmer