using System.Collections; using System.Collections.Generic; using UnityEngine; public class Move : MonoBehaviour { public float SPEED = 10.0f; private Vector2 SCREEN_MAX; private Vector2 SCREEN_MIN; private Vector2 SELF_EXTENTS; private Vector2 _velocity = Vector2.zero; // Start is called before the first frame update void Start() { // get screen size from camera (convert viewport 0,0 and 1,1 to world) SCREEN_MAX = Camera.main.ViewportToWorldPoint(new Vector2(1,1)); SCREEN_MIN = Camera.main.ViewportToWorldPoint(Vector2.zero); // get self size from the sprite // bounds.extents is the half width/height of the sprite in world units SELF_EXTENTS = (Vector3)transform.GetComponent().sprite.bounds.extents; } // Update is called once per frame void Update() { // convert user input into a movement direction (could use Unity axis for this) Vector2 dir = Vector2.zero; if (Input.GetKey(KeyCode.D)) dir += Vector2.right; if (Input.GetKey(KeyCode.A)) dir += Vector2.left; if (Input.GetKey(KeyCode.W)) dir += Vector2.up; if (Input.GetKey(KeyCode.S)) dir += Vector2.down; // set velocity based on movement direction _velocity = dir.normalized * SPEED; // integrate velocity to update position transform.position = transform.position + (Vector3)(_velocity * Time.deltaTime); // detect wall collisions and respond // (removed until assn02 is done) // detect game ending collisions GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject enemy in enemies) { float r = enemy.GetComponent().GetRadius(); float min_dist = r + SELF_EXTENTS.x; Vector2 diff = transform.position - enemy.transform.position; float dist = diff.magnitude; if (dist < min_dist) { // quit either from the editor or from a built application #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif } } } }