using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; using UnityEngine.InputSystem; public class PlayerController : MonoBehaviour { public Light2D nuzzleFlash; private Rigidbody2D rb; private SpriteRenderer sr; private Camera main; //Input private PlayerInput input; private InputAction moveAction; private InputAction fightAction; private Vector2 moveDirection; private float moveSpeed = 5f; //Shooting public GameObject bulletPrefab; private bool isShooting = false; private float lastShot = 0f; private float shootSpeed = 0.25f; // Start is called before the first frame update private void Awake() { rb = this.gameObject.GetComponent(); input = this.gameObject.GetComponent(); moveAction = input.actions["Move"]; fightAction = input.actions["Fight"]; //Input events moveAction.performed += ctx => Move(ctx.ReadValue()); moveAction.canceled += ctx => Move(Vector2.zero); fightAction.performed += ctx => Fight(); fightAction.canceled += ctx => Fight(true); main = Camera.main; } private void FixedUpdate() { //Update move direction rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime); } private void Update() { //Update the sprite direction based on mouse position Vector2 mousePos = main.ScreenToWorldPoint(Mouse.current.position.ReadValue()); Vector2 direction = mousePos - (Vector2)transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); //shooting if(isShooting && Time.time - lastShot > shootSpeed) { lastShot = Time.time; Instantiate(bulletPrefab, transform.position, transform.rotation); nuzzleFlash.intensity = 2f; Invoke(nameof(disableNuzzleFlash), 0.025f); } } //update the move direction void Move(Vector2 direction) => moveDirection = direction; //Shoot void Fight(bool stop = false) { isShooting = !stop; } void disableNuzzleFlash() { nuzzleFlash.intensity = 0f; } }