2015-04-11 3 views
0

Я возился в Unity и хотел сделать механика, где коробка коснется другого объекта, а затем этот объект будет следовать за игроком.Объект, следующий за игроком

У меня есть куб настроить так: Cube Inspector

И Sphere с Box Collider с такими же параметрами.

Мой сценарий игрока таким образом:

public class Player : MonoBehaviour { 

public float speed = 0.0f; 
public float moveX = 0.0f; 
public float moveY = 0.0f; 
public GameObject player; 
public GameObject obj; 
//public float force = 0.0f; 
private bool collided = false; 


// Use this for initialization 
void Start() { 
    player = GameObject.FindWithTag ("Player"); 
} 

// Update is called once per frame 
void FixedUpdate() { 
    moveX = Input.GetAxis ("Horizontal"); 
    moveY = Input.GetAxis ("Vertical"); 
    player.GetComponent<Rigidbody>().velocity = new Vector2 (moveX * speed, moveY * speed);  
} 

void OnCollisionEnter (Collision col) { 
    if (col.gameObject == obj) { 
     collided = true; 
    } 
} 

void OnCollisionExit (Collision col) { 
    if (col.gameObject == obj) { 
     collided = false; 
    } 
} 

void Update() { 
    if(collided) { 
     obj.transform.position = (player.transform.position - obj.transform.position)*speed; 
    } 
} 

} 

Что я еще делать? Надеясь, кто-то может подтолкнуть меня в правильном направлении.

+0

Я редактировал свой титул. Пожалуйста, смотрите: «Если вопросы включают« теги »в их названиях?] (Http://meta.stackexchange.com/questions/19190/), где консенсус« нет, они не должны ». –

ответ

1

Я дам вам два сценария.

1-й скрипт - FollowTarget. Это будет следовать вашей цели.

2nd Script - SmoothFollow, который будет следовать за вашей целью в плавном движении.

FollowTarget.cs
using System; 
using UnityEngine; 

public class FollowTarget : MonoBehaviour 
{ 
    public Transform target; 
    public Vector3 offset = new Vector3(0f, 7.5f, 0f); 


    private void LateUpdate() 
    { 
     transform.position = target.position + offset; 
    } 
} 

SmoothFollow.cs
using UnityEngine; 


public class SmoothFollow : MonoBehaviour 
{ 

    // The target we are following 
    [SerializeField] 
    private Transform target; 
    // The distance in the x-z plane to the target 
    [SerializeField] 
    private float distance = 10.0f; 
    // the height we want the camera to be above the target 
    [SerializeField] 
    private float height = 5.0f; 

    [SerializeField] 
    private float rotationDamping; 
    [SerializeField] 
    private float heightDamping; 

    // Use this for initialization 
    void Start() { } 

    // Update is called once per frame 
    void LateUpdate() 
    { 
     // Early out if we don't have a target 
     if (!target) 
      return; 

     // Calculate the current rotation angles 
     var wantedRotationAngle = target.eulerAngles.y; 
     var wantedHeight = target.position.y + height; 

     var currentRotationAngle = transform.eulerAngles.y; 
     var currentHeight = transform.position.y; 

     // Damp the rotation around the y-axis 
     currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime); 

     // Damp the height 
     currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime); 

     // Convert the angle into a rotation 
     var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); 

     // Set the position of the camera on the x-z plane to: 
     // distance meters behind the target 
     transform.position = target.position; 
     transform.position -= currentRotation * Vector3.forward * distance; 

     // Set the height of the camera 
     transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z); 

     // Always look at the target 
     transform.LookAt(target); 
    } 
} 

Просто выберите одну из них, а затем прикрепить его к геймобжекты. Как и в другой коробке, которая должна следовать.

Удалите функцию Update() в своем скрипте, поскольку она вам больше не нужна.

Также Удалите OnCollisionExit()

void OnCollisionEnter (Collision col) { 
    if (col.gameObject == obj) { 

     // If you choose to use SmoothFollow Uncomment this. 
     //col.GetComponent<SmoothFollow>().target = this.transform; 

     // If you choose to use FollowTarget Uncomment this 
     //col.GetComponent<FollowTarget>().target = this.transform; 
    } 
}