This repository has been archived on 2024-11-28. You can view files and clone it, but cannot push or open issues or pull requests.
PMC_Projekt/ProjektUnity/Assets/Scripts/Player/Shooting.cs
2024-09-06 11:38:44 +02:00

75 lines
1.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using Unity.IO.LowLevel.Unsafe;
using UnityEngine;
//Ben Keller
public class Shooting : MonoBehaviour
{
private Camera mainCam;
private Vector3 mousePos;
public GameObject bulletPref;
public Transform bulletTransform;
public bool canFire;
private float timer;
public PlayerStats playerStats;
SpriteRenderer spriteRenderer;
public Transform muzzle;
void Start()
{
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
playerStats = gameObject.GetComponentInParent<PlayerStats>();
spriteRenderer = gameObject.GetComponentInChildren<SpriteRenderer>();
}
void Update()
{
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = mousePos - transform.position;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rotZ);
flip();
fire();
}
void flip(){
if (mousePos.x < transform.position.x)
{
spriteRenderer.flipY = true;
muzzle.localPosition = new Vector3(1.65f, -0.14f, 0);
}
else
{
spriteRenderer.flipY = false;
muzzle.localPosition = new Vector3(1.65f, 0.14f, 0);
}
}
void fire(){
if(!canFire){
timer += Time.deltaTime;
if(timer > playerStats.fireRate){
canFire = true;
timer = 0;
}
}
if(Input.GetMouseButton(0) && canFire){
canFire = false;
Instantiate(bulletPref, bulletTransform.position, Quaternion.identity);
}
}
}