When my character moves, I want the camera to follow them, such that the character always stays in the middle of the view. How do I do that in Unity?
Here's my code right now:
using UnityEngine;
using System.Collections;
public class CharacterControll : MonoBehaviour {
public float speed = 3f;
private Animator animator;
private Vector2 screenSW;
private Vector2 screenNE;
private float wrapPadding = 1f;
public GameObject gameObject;
// Use this for initialization
void Start () {
animator = this.GetComponent ();
screenSW = Camera.main.ScreenToWorldPoint (new Vector2(0, 0));
screenNE = Camera.main.ScreenToWorldPoint (new Vector2(Screen.width, Screen.height));
}
// Update is called once per frame
void Update () {
float horizontalInput = Input.GetAxis ("Horizontal");
float verticalInput = Input.GetAxis ("Vertical");
if (horizontalInput == 0) {
animator.speed = 0;
animator.SetInteger("Direction", 0);
}
else if (horizontalInput < 0) {
animator.speed = 3;
animator.SetInteger("Direction", 1);
}
transform.Translate (Vector2.right * horizontalInput * Time.deltaTime * speed);
transform.Translate (Vector2.up * verticalInput * Time.deltaTime * speed);
if (transform.localPosition.x < screenSW.x - wrapPadding) {
transform.localPosition = new Vector2(screenNE.x, transform.localPosition.y);
}
else if (transform.localPosition.x > screenNE.x + wrapPadding) {
transform.localPosition = new Vector2(screenSW.x, transform.localPosition.y);
}
}
void OnTriggerEnter2d(Collider2D other){
}
}
Answer
Just make the main camera a child of the player object in the hierarchy, then move it to where you want it in the scene view with the translate/rotate tools. Don't make it overly complicated with code.
Or apply the same control scripts and colliders to the camera as to the player object.
No comments:
Post a Comment