Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created June 12, 2018 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithweaver/e42183d447668c56b923d4e388ff2086 to your computer and use it in GitHub Desktop.
Save keithweaver/e42183d447668c56b923d4e388ff2086 to your computer and use it in GitHub Desktop.
Move the camera when the mouse reaches the edge of the screen.
// Attach to the camera asset
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCamera : MonoBehaviour {
private int screenWidth;
private int screenHeight;
public int speed = 5;
public int distanceFromBoundary = 50;
// Use this for initialization
void Start () {
screenWidth = Screen.width;
screenHeight = Screen.height;
}
// Update is called once per frame
void Update () {
Vector3 position = transform.position;
if (Input.mousePosition.x > screenWidth - distanceFromBoundary) {
position.x += speed * Time.deltaTime; // move on +X axis
}
if (Input.mousePosition.x < 0 + distanceFromBoundary) {
position.x -= speed * Time.deltaTime; // move on -X axis
}
if (Input.mousePosition.y > screenHeight - distanceFromBoundary) {
position.z += speed * Time.deltaTime; // move on +Z axis
}
if (Input.mousePosition.y < 0 + distanceFromBoundary) {
position.z -= speed * Time.deltaTime; // move on -Z axis
}
transform.position = position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment