84 lines
2.3 KiB
C#
84 lines
2.3 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
public class CannonScript : MonoBehaviour
|
|
{
|
|
[SerializeField] private GameObject cannon;
|
|
[SerializeField] private GameObject projectile;
|
|
[SerializeField] private float lookDepth;
|
|
[SerializeField] private float cannonForce;
|
|
[SerializeField] private float fireRate = 0.5f;
|
|
[SerializeField]private float fireTimer;
|
|
private bool firing = false;
|
|
|
|
[SerializeField]private float damage = 1f;
|
|
private Vector3 lookDir;
|
|
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
lookDir = Vector3.zero;
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
if(firing){
|
|
fireTimer += Time.deltaTime;
|
|
if(fireTimer >= fireRate){
|
|
GameObject proj = Instantiate(projectile, transform.position, cannon.transform.rotation);
|
|
proj.GetComponent<Projectile>().SetDamage(damage);
|
|
proj.GetComponent<Rigidbody>().AddForce(cannonForce * lookDir, ForceMode.Impulse);
|
|
fireTimer = 0;
|
|
}
|
|
}else if(fireTimer < fireRate){
|
|
fireTimer += Time.deltaTime;
|
|
}
|
|
}
|
|
|
|
private Vector3 GetMouseWorldPosition(){
|
|
Vector3 screenPos = Mouse.current.position.ReadValue();
|
|
screenPos.z = lookDepth;
|
|
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPos);
|
|
|
|
return worldPoint;
|
|
}
|
|
|
|
public void OnLook(InputAction.CallbackContext ctx){
|
|
Vector3 bodyLookPos= GetMouseWorldPosition(), cannonLookPos = GetMouseWorldPosition();
|
|
bodyLookPos.y = 0;
|
|
gameObject.transform.LookAt(bodyLookPos);
|
|
cannon.transform.LookAt(cannonLookPos);
|
|
lookDir = (cannonLookPos - transform.position).normalized;
|
|
}
|
|
|
|
public void OnFire(InputAction.CallbackContext ctx){
|
|
if(ctx.started){//btn pressed
|
|
firing = true;
|
|
}else if(ctx.canceled){//btn released
|
|
firing = false;
|
|
|
|
}
|
|
}
|
|
|
|
public void SetFireRate(float nFireRate){
|
|
this.fireRate = nFireRate;
|
|
}
|
|
|
|
public float GetFireRate(){
|
|
return fireRate;
|
|
}
|
|
|
|
public void SetDamage(float dmg){
|
|
this.damage = dmg;
|
|
}
|
|
|
|
public float GetDamage(){
|
|
return damage;
|
|
}
|
|
|
|
}
|