82 lines
2.5 KiB
C#
82 lines
2.5 KiB
C#
using UnityEngine;
|
|
#if ENABLE_INPUT_SYSTEM
|
|
using UnityEngine.InputSystem;
|
|
#endif
|
|
namespace KD.Destro2D{
|
|
public class BasicPlayerControl2D : MonoBehaviour
|
|
{
|
|
#if ENABLE_INPUT_SYSTEM
|
|
public InputActionAsset inputActions;
|
|
public float bulletCD;
|
|
InputAction move;
|
|
InputAction missileAttack;
|
|
InputAction bulletAttack;
|
|
Rigidbody2D rb;
|
|
public float speed;
|
|
Vector2 lookDirn;
|
|
Vector2 dirn;
|
|
public GameObject missilePrefab;
|
|
public GameObject bulletPrefab;
|
|
public float missileSpeed;
|
|
public float shootOffset;
|
|
float t;
|
|
void OnEnable()
|
|
{
|
|
move = inputActions.FindAction("Player/Move",true);
|
|
missileAttack = inputActions.FindAction("Player/AltAttack",true);
|
|
bulletAttack = inputActions.FindAction("Player/Attack",true);
|
|
missileAttack.Enable();
|
|
bulletAttack.Enable();
|
|
move.Enable();
|
|
rb = GetComponent<Rigidbody2D>();
|
|
}
|
|
void Start()
|
|
{
|
|
missileAttack.performed += _ => ShootMissile(missilePrefab);
|
|
|
|
}
|
|
void OnDisable()
|
|
{
|
|
missileAttack.Disable();
|
|
bulletAttack.Disable();
|
|
move.Disable();
|
|
}
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
t+=Time.deltaTime;
|
|
Move();
|
|
Look();
|
|
if(bulletAttack.IsPressed()){
|
|
if(t < bulletCD) return;
|
|
ShootMissile(bulletPrefab);
|
|
t = 0;
|
|
}
|
|
}
|
|
void FixedUpdate()
|
|
{
|
|
rb.AddForce(dirn);
|
|
}
|
|
void ShootMissile(GameObject prefab)
|
|
{
|
|
float angle = Mathf.Atan2(lookDirn.y,lookDirn.x) * Mathf.Rad2Deg;
|
|
Quaternion missileRotn = Quaternion.AngleAxis(angle,transform.forward);
|
|
Rigidbody2D missile = Instantiate(prefab,(Vector2)transform.position + lookDirn.normalized * shootOffset,missileRotn).GetComponent<Rigidbody2D>();
|
|
missile.AddForce(lookDirn.normalized * missileSpeed);
|
|
}
|
|
void Look()
|
|
{
|
|
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
|
|
mousePos.z = transform.position.z;
|
|
lookDirn = mousePos - transform.position;
|
|
}
|
|
void Move()
|
|
{
|
|
float dirval = move.ReadValue<float>();
|
|
dirn = transform.right * dirval * speed;
|
|
|
|
}
|
|
#endif
|
|
}
|
|
|
|
} |