2013-06-13 3 views
0

대각선으로 물체를 움직이는 컨트롤러가 있습니다. 왼쪽 화살표는 플레이어를 앞으로 그리고 왼쪽으로 45도 이동시키고 오른쪽 화살표는 오른쪽으로 이동해야합니다. 플레이어를 현재 위치로 상대적으로 이동시키고 싶습니다. 지금은 상대적으로 점 (0,0,0)으로 이동합니다. 내 코드Unity 3d에서 고정 거리를 어떻게 이동합니까?

:

public class JollyJumper : MonoBehaviour { 

protected CharacterController control; 
    public float fTime = 1.5f;  // Hop time 
    public float fRange = 5.0f;  // Max dist from origin 
    public float fHopHeight = 2.0f; // Height of hop 

    private Vector3 v3Dest; 
    private Vector3 v3Last; 
    private float fTimer = 0.0f; 
    private bool moving = false; 
    private int number= 0; 
    private Vector2 direction; 

    public virtual void Start() { 

     control = GetComponent<CharacterController>(); 

     if(!control){ 

      Debug.LogError("No Character Controller"); 
      enabled=false; 

     } 

    } 


    void Update() { 

     if (fTimer >= fTime&& moving) { 
     var playerObject = GameObject.Find("Player"); 
     v3Last = playerObject.transform.position; 
     Debug.Log(v3Last); 
     v3Dest = direction *fRange; 
     //v3Dest = newVector* fRange + v3Last; 

     v3Dest.z = v3Dest.y; 
     v3Dest.y = 0.0f; 
     fTimer = 0.0f; 
     moving = false; 
     } 

     if(Input.GetKeyDown(KeyCode.LeftArrow)){ 
      moving = true; 
      direction = new Vector2(1.0f, 1.0f); 
      number++; 
     } 

     if(Input.GetKeyDown(KeyCode.RightArrow)){ 
      moving = true; 
      direction = new Vector2(-1.0f, 1.0f); 
      number++; 
     } 
     if(moving){ 
     Vector3 v3T = Vector3.Lerp (v3Last, v3Dest, fTimer/fTime); 
     v3T.y = Mathf.Sin (fTimer/fTime * Mathf.PI) * fHopHeight; 
     control.transform.position = v3T; 
     fTimer += Time.deltaTime; 
     } 
    } 
} 

어떻게이 문제를 해결할 수 있습니까? 어떤 아이디어? 고마워요!

답변

5

짧은 대답은 : 당신은 당신이로 이동하고자하는 두 위치를 하드 코딩 : 점 (1, 1), (-1, 1). 점프를 시작할 때마다 새 Vector를 만들어야합니다.

v3Dest = transform.position + new Vector3(1.0f, 0, 1) * fRange; 

을하고 그것을 작동합니다 :이 줄을 각

direction = new Vector2(1.0f, 1.0f); 

를 교체합니다. 내가에있어 동안

, 내가 지적하고 싶은 다른 일이 있습니다

  • 각 점프 후 지점 오류 부동의 많은있다. 당신이 moving 플래그 이전에 전환하기 때문에 코드에서 v3Tv3Dest 동일 결코 것을 주목 (실제로 목적지에 도달하지 않음). 점프가 끝나면 명시 적으로 위치를 v3Dest으로 설정해야합니다.
  • 당신은 등 모든 프레임 점프 타이머를 확인하고 있습니다. 좀 더 엘레강스 한 해결책은 start a coroutine입니다.
  • 당신은 괜찮아 보이는 당신의 점프 곡선으로 사인 곡선을 사용하지만, 포물선을 사용하는 것은 개념적으로 더 정확한 것입니다.
  • 은 지금은 여기

당신이 그것을 사용할 수있는 몇 가지 코드입니다 (그것이 의도 여부 잘 모르겠어요) 다음 점프는 공중을 시작할 수 이러한 문제 방지 :

using System.Collections; 
using UnityEngine; 

public class Jumper : MonoBehaviour 
{ 
#region Set in editor; 

public float jumpDuration = 0.5f; 
public float jumpDistance = 3; 

#endregion Set in editor; 

private bool jumping = false; 
private float jumpStartVelocityY; 

private void Start() 
{ 
    // For a given distance and jump duration 
    // there is only one possible movement curve. 
    // We are executing Y axis movement separately, 
    // so we need to know a starting velocity. 
    jumpStartVelocityY = -jumpDuration * Physics.gravity.y/2; 
} 

private void Update() 
{ 
    if (jumping) 
    { 
     return; 
    } 
    else if (Input.GetKeyDown(KeyCode.LeftArrow)) 
    { 
     // Warning: this will actually move jumpDistance forward 
     // and jumpDistance to the side. 
     // If you want to move jumpDistance diagonally, use: 
     // Vector3 forwardAndLeft = (transform.forward - transform.right).normalized * jumpDistance; 
     Vector3 forwardAndLeft = (transform.forward - transform.right) * jumpDistance; 
     StartCoroutine(Jump(forwardAndLeft)); 
    } 
    else if (Input.GetKeyDown(KeyCode.RightArrow)) 
    { 
     Vector3 forwardAndRight = (transform.forward + transform.right) * jumpDistance; 
     StartCoroutine(Jump(forwardAndRight)); 
    } 
} 

private IEnumerator Jump(Vector3 direction) 
{ 
    jumping = true; 
    Vector3 startPoint = transform.position; 
    Vector3 targetPoint = startPoint + direction; 
    float time = 0; 
    float jumpProgress = 0; 
    float velocityY = jumpStartVelocityY; 
    float height = startPoint.y; 

    while (jumping) 
    { 
     jumpProgress = time/jumpDuration; 

     if (jumpProgress > 1) 
     { 
      jumping = false; 
      jumpProgress = 1; 
     } 

     Vector3 currentPos = Vector3.Lerp(startPoint, targetPoint, jumpProgress); 
     currentPos.y = height; 
     transform.position = currentPos; 

     //Wait until next frame. 
     yield return null; 

     height += velocityY * Time.deltaTime; 
     velocityY += Time.deltaTime * Physics.gravity.y; 
     time += Time.deltaTime; 
    } 

    transform.position = targetPoint; 
    yield break; 
} 

}

+0

모든 코드 조각 날 줄 수 있습니까? 나는 프로그래밍에서 경험했지만 Unity3d에서는 경험하지 못했습니다. –

+0

Unity Inspector에서 플레이어를 플레이어로 끌어 놓기 만하면됩니다. 런타임 중에 이들 중 하나를 생성하면'controller.transform.parent = player.transform'을 설정하십시오. –

+0

죄송합니다. 질문을 수정하여 명확하게 처리했습니다. 나는 플레이어가 오른쪽과 왼쪽으로 뛰어 넘을 수는 없다. palyer가 상대적으로 (0, 0, 0)으로 이동하기 때문에 v3dest를 계속 증가시켜야합니다. –

관련 문제