2016-06-09 4 views
0

대원 스크립트가 플레이어를 따르지 않는 이유는 무엇입니까?대원 스크립트가 플레이어를 따르지 않는 이유는 무엇입니까?

using UnityEngine; 
using System.Collections; 

public class suivre : MonoBehaviour { 

    GameObject perso; 
    float persoposx; 
    float persoposy; 
    float persoposz; 

    // Use this for initialization 
    void Start() { 
     perso = GameObject.FindGameObjectWithTag ("Player"); 
     InvokeRepeating ("follower", 1, 1); 
    } 

    // Update is called once per frame 
    void Update() { 
     persoposx = perso.transform.position.x; 
     persoposy = perso.transform.position.y; 
     persoposz = perso.transform.position.z; 

    } 

    void follower() { 

     GetComponent<Rigidbody>().AddForce(new Vector3(persoposx, persoposy, persoposz)); 
    } 
} 

이 스크립트는 적의 구성 요소입니다. 적이 플레이어를 따라 가지 않지만 여전히 방향으로 향합니다 - 왜?

+1

플레이어의 위치 데이터를 전혀 사용하지 않는 것처럼 보입니다. 여러분은 항상 x 축을 따라'new Vector3 (1, 0, 0)'을 사용하여 적을 움직일 수는 있지만 플레이어의 방향으로 움직이지는 않습니다. – Serlite

+2

Bonjour JohnD, 큰 문제가 있습니다. Update 내에서 InvokeRepeating을 호출하는 것은 절대 불가능합니다. 애호가 프로그래밍 여행을 시작하려면 많은 뛰어난 Unity 튜토리얼을 다시 시작해야합니다. – Fattie

+0

내 코드를 편집했지만 아무 일도 일어나지 않습니다. –

답변

1

방향 벡터의 한 개념이 누락되었습니다.

코드는 그 같이한다 :

using UnityEngine; 
using System.Collections; 

public class suivre : MonoBehaviour 
{  
    public float speed = 3f; 

    GameObject perso; 

    void Start() 
    { 
     perso = GameObject.FindGameObjectWithTag ("Player"); 
     InvokeRepeating ("follower", 1, 1); 
    } 

    void follower() 
    {  
     Vector3 directionToPlayer = perso.transform.position - this.transform.position; 
     directionToPlayer.Normalize(); 

     GetComponent<Rigidbody>().AddForce(directionToPlayer * speed); 
    } 
} 

는 업데이트 방법 제거하십시오. 너는 여기 필요 없어.

그런 다음 적과 플레이어 간의 방향 벡터를 만들고이를 정규화 한 다음이 벡터를 AddForce에 전달하고 원하는 속도로 곱하십시오.

관련 문제