You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.2 KiB
76 lines
2.2 KiB
using System; |
|
using System.Collections; |
|
using System.Collections.Generic; |
|
using UnityEngine; |
|
using UnityEngine.InputSystem; |
|
|
|
public class PlayerController : MonoBehaviour |
|
{ |
|
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.5f; |
|
|
|
|
|
// Start is called before the first frame update |
|
private void Awake() |
|
{ |
|
rb = this.gameObject.GetComponent<Rigidbody2D>(); |
|
input = this.gameObject.GetComponent<PlayerInput>(); |
|
moveAction = input.actions["Move"]; |
|
fightAction = input.actions["Fight"]; |
|
|
|
//Input events |
|
moveAction.performed += ctx => Move(ctx.ReadValue<Vector2>()); |
|
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); |
|
} |
|
} |
|
|
|
//update the move direction |
|
void Move(Vector2 direction) => moveDirection = direction; |
|
|
|
//Shoot |
|
void Fight(bool stop = false) |
|
{ |
|
isShooting = !stop; |
|
} |
|
} |