Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.EventSystems;
- public class ShootController : MonoBehaviour
- {
- private LevelController levelController;
- public float bulletMass = 1;
- private LineDrawer lineDrawer;
- private Vector2 shootDir = new Vector2();
- public Transform gun;
- public Transform rayStart;
- public bool isFlip = false;
- private bool wasDown = false;
- private void Awake()
- {
- levelController = FindObjectOfType<LevelController>();
- }
- private void Start()
- {
- lineDrawer = new LineDrawer(0.05f);
- }
- void Update()
- {
- var fingerId = PointerInputModule.kMouseLeftId;
- if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
- {
- fingerId = Input.GetTouch(0).fingerId;
- }
- if (levelController.canShoot())
- {
- if (EventSystem.current.IsPointerOverGameObject(fingerId))
- return;
- if (Input.GetMouseButtonDown(0))
- {
- lineDrawer.enable(true);
- wasDown = true;
- }
- if (wasDown)
- {
- if (Input.GetMouseButton(0))
- updateAim(Input.mousePosition);
- if (Input.GetMouseButtonUp(0))
- {
- GoFabric.createBullet(rayStart.position, shootDir, bulletMass);
- AudioController.Instance.PlaySound(Sounds.Shot);
- EventManager.TriggerEvent(new Events.ShotEvent(shootDir.x));
- wasDown = false;
- }
- }
- }
- if (Input.GetMouseButtonUp(0))
- {
- lineDrawer.enable(false);
- }
- }
- private void updateAim(Vector2 touchPos)
- {
- var mouseWorldPosition = Camera.main.ScreenToWorldPoint(touchPos);
- var pos = rayStart.position;
- var gunDirection = new Vector2(
- mouseWorldPosition.x - gun.position.x,
- mouseWorldPosition.y - gun.position.y
- );
- gun.right = gunDirection;
- shootDir = gunDirection;
- lineDrawer.DrawLineInGameView(pos, pos + (Vector3) (gunDirection * 200), new Color(1, 0, 0, 0.5f));
- gunDirection = new Vector2(
- mouseWorldPosition.x - transform.position.x,
- mouseWorldPosition.y - transform.position.y
- );
- FlipHero(gunDirection);
- }
- private void FlipHero(Vector2 dir)
- {
- var angle = dir.Angle();
- var flip = angle >= 90 && angle <= 270;
- gun.transform.localScale = new Vector3(flip ? -1 : 1, flip ? -1 : 1, 1);
- transform.localScale = new Vector3(flip ? 1 : -1, 1, 1);
- }
- bool IsPointerOverGameObject( int fingerId )
- {
- EventSystem eventSystem = EventSystem.current;
- return ( eventSystem.IsPointerOverGameObject( fingerId )
- && eventSystem.currentSelectedGameObject != null );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement