Advertisement
LeeMace

Player Movement and Kept Inbounds

Nov 29th, 2022
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class playerController : MonoBehaviour
  6. {
  7.     public float horizontalInput;
  8.     public float verticalInput;
  9.  
  10.     public float speed = 10.0f;
  11.     //range for which player can move left and right
  12.     public float xRange = 10;
  13.     //range for which player can move froward and back
  14.     public float zRange = 10;
  15.     //slot for food
  16.     public GameObject projectilePrefab;
  17.  
  18.     public Transform projectileSpawnPoint;
  19.     void Start()
  20.     {
  21.        
  22.     }
  23.  
  24.     void Update()
  25.     {
  26.         //keep player inbounds on the left side
  27.         if (transform.position.x < -xRange)
  28.         {
  29.         transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
  30.         }
  31.         //keep player inbounds on the right side
  32.         if (transform.position.x > xRange)
  33.         {
  34.             transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
  35.         }
  36.  
  37.  
  38.         //move the player left and right
  39.         horizontalInput = Input.GetAxis("Horizontal");
  40.         transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);
  41.  
  42.         //move the player forward and back
  43.         verticalInput = Input.GetAxis("Vertical");
  44.         transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed);
  45.  
  46.  
  47.         //keep player inbounds on the lower side
  48.         if (transform.position.z < -zRange)
  49.         {
  50.             transform.position = new Vector3(transform.position.x, transform.position.y, -zRange);
  51.         }
  52.         //keep player inbounds on the upper side
  53.         if (transform.position.z > zRange)
  54.         {
  55.             transform.position = new Vector3(transform.position.x, transform.position.y, zRange);
  56.         }
  57.  
  58.  
  59.         //launch projectile using spacebar
  60.         if (Input.GetKeyDown(KeyCode.Space))
  61.         {
  62.             Instantiate(projectilePrefab, projectileSpawnPoint.position, projectilePrefab.transform.rotation); ;
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement