Skip to content

Instantly share code, notes, and snippets.

@jbasinger
Created May 21, 2015 20:40
Show Gist options
  • Save jbasinger/cc872a26196b5c6a4e26 to your computer and use it in GitHub Desktop.
Save jbasinger/cc872a26196b5c6a4e26 to your computer and use it in GitHub Desktop.
Intro to Unity
using UnityEngine;
using System.Collections;
public class ClipToCameraBounds : MonoBehaviour {
private float minPos;
private float maxPos;
private SpriteRenderer renderer;
// Use this for initialization
void Start () {
renderer = this.gameObject.GetComponent<SpriteRenderer>();
float halfSize = renderer.bounds.size.x/2;
minPos = Camera.main.ScreenToWorldPoint(Vector3.zero).x + halfSize;
maxPos = Camera.main.ScreenToWorldPoint(new Vector3(Camera.main.pixelWidth,0)).x - halfSize;
Debug.Log(minPos);
Debug.Log(maxPos);
}
// Update is called once per frame
void Update () {
//this.transform.position = new Vector2(Mathf.Clamp(this.transform.position.x,minPos,maxPos), this.transform.position.y);
}
void LateUpdate(){
this.transform.position = new Vector2(Mathf.Clamp(this.transform.position.x,minPos,maxPos), this.transform.position.y);
}
}
using UnityEngine;
using System.Collections;
public class MoveLeftAndRight : MonoBehaviour {
public float speed;
//Rigidbody2D body;
// Use this for initialization
void Start () {
//body = this.gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow)){
float magnitude = speed * Time.deltaTime;
if(Input.GetKey(KeyCode.LeftArrow)){
magnitude *= -1;
}
//body.velocity = new Vector2(magnitude,0);
this.transform.position = new Vector2(this.transform.position.x+magnitude, this.transform.position.y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment