42 lines
1.3 KiB
C#
42 lines
1.3 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class PlayerWeapon : MonoBehaviour
|
|
{
|
|
// Copied and modified from https://answers.unity.com/questions/696001/how-to-make-bullet-shoot-in-same-direction-as-play.html
|
|
|
|
public Camera sceneCamera;
|
|
public Rigidbody2D bullet;
|
|
public float attackSpeed = 0.5f;
|
|
public float bulletSpeed = 600;
|
|
|
|
private Rigidbody2D _player;
|
|
private float _cooldown;
|
|
|
|
private void Start()
|
|
{
|
|
_player = GetComponent<Rigidbody2D>();
|
|
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
Vector2 mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
|
|
Vector2 playerPosition = _player.position;
|
|
|
|
if (!(Time.time >= _cooldown) || !Input.GetMouseButton(0)) return;
|
|
Fire(playerPosition, mousePosition);
|
|
}
|
|
|
|
private void Fire(Vector2 from, Vector2 towards)
|
|
{
|
|
Rigidbody2D firingBullet = Instantiate(bullet, _player.transform);
|
|
// TODO does it matter that GetComponent is expensive?
|
|
Physics2D.IgnoreCollision(firingBullet.GetComponent<Collider2D>(), _player.GetComponent<Collider2D>());
|
|
Vector2 direction = towards - from;
|
|
firingBullet.AddForce(direction.normalized * bulletSpeed + _player.velocity);
|
|
|
|
_cooldown = Time.time + attackSpeed;
|
|
}
|
|
}
|