Facebook
From Cameron Nepe, 3 Years ago, written in C#.
Embed
Download Paste or View Raw
Hits: 74
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Player : MonoBehaviour
  6. {
  7.     // configuration parameters
  8.     [SerializeField] float moveSpeed = 10f;
  9.     [SerializeField] float padding = 1f;
  10.     [SerializeField] GameObject laserPrefab;
  11.     [SerializeField] float projectileSpeed = 10f;
  12.  
  13.     float xMin;
  14.     float xMax;
  15.     float yMin;
  16.     float yMax;
  17.  
  18.     // Start is called before the first frame update
  19.     void Start()
  20.     {
  21.         transform.position = new Vector3(0, -8, 0);
  22.         SetUpMoveBoundaries();
  23.     }
  24.  
  25.     // Update is called once per frame
  26.     void Update()
  27.     {
  28.         Move();
  29.         Fire();
  30.     }
  31.  
  32.     private void Fire()
  33.     {
  34.         if (Input.GetButtonDown("Fire1"))
  35.         {
  36.             GameObject laser = Instantiate
  37.                 (
  38.                 laserPrefab,
  39.                 transform.position,
  40.                 Quaternion.identity
  41.                 ) as GameObject ;
  42.             laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
  43.         }
  44.     }
  45.  
  46.     private void Move()
  47.     {
  48.         float deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
  49.         float deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
  50.  
  51.         float newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
  52.         float newYPos = Mathf.Clamp(transform.position.x + deltaY, yMin, yMax);
  53.  
  54.         transform.position = new Vector2(newYPos, newXPos);
  55.     }
  56.  
  57.     private void SetUpMoveBoundaries()
  58.     {
  59.         Camera gameCamera = Camera.main;
  60.         xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + padding;
  61.         xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - padding;
  62.         yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + padding;
  63.         yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y - padding;
  64.     }
  65. }