Unity 2D – How to anchor a sprite to the left side of the camera viewport

using UnityEngine;
using System.Collections;

public class ActualHeroController : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
float camHalfHeight = Camera.main.orthographicSize;
float camHalfWidth = Camera.main.aspect * camHalfHeight;

Bounds bounds = GetComponent().bounds;

// Set a new vector to the top left of the scene
Vector3 topLeftPosition = new Vector3(-camHalfWidth, 0, 0) + Camera.main.transform.position;

// Offset it by the size of the object
topLeftPosition += new Vector3(bounds.size.x / 2,-bounds.size.y / 2, 0);
topLeftPosition.z = 0;
transform.position = topLeftPosition;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *