Created
August 20, 2020 11:31
-
-
Save inertiave/54f9206fb493615d3ce4a18633229531 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
public class Shooter : MonoBehaviour { | |
public LayerMask layerMask; | |
public Camera mainCamera; | |
public Transform target; | |
public Rigidbody bullet; | |
public Transform muzzle; | |
public int fireCount = 1; | |
public float speed = 10f; | |
public float threshold = 1f; | |
public float fireDelay = 0.14f; | |
public float bulletPower = 10f; | |
public float bulletLifeTime = 2f; | |
public float bulletAngle = 15f; | |
Vector3 targetPosition; | |
bool isMoving; | |
bool isFiring; | |
// Update is called once per frame | |
void Update() | |
{ | |
RaycastHit hit; | |
Vector3 mos = Input.mousePosition; | |
mos.z = mainCamera.farClipPlane; | |
Vector3 dir = mainCamera.ScreenToWorldPoint(mos); | |
Debug.DrawRay(mainCamera.transform.position, mainCamera.transform.position + mos.z * 2 * dir); | |
if (Physics.Raycast(mainCamera.transform.position, dir, out hit, 2 * mos.z, layerMask)) { | |
transform.LookAt(hit.point); | |
} | |
if (Input.GetMouseButtonDown(1)) { | |
target.position = hit.point; | |
targetPosition = hit.point; | |
isMoving = true; | |
} | |
if (Input.GetMouseButtonDown(0)) { | |
isFiring = true; | |
StartCoroutine(nameof(Fire)); | |
} | |
if (Input.GetMouseButtonUp(0)) { | |
isFiring = false; | |
StopCoroutine(nameof(Fire)); | |
} | |
} | |
IEnumerator Fire() | |
{ | |
while (isFiring) { | |
yield return null; | |
DoFire(); | |
yield return new WaitForSeconds(fireDelay); | |
} | |
} | |
void DoFire() | |
{ | |
for (int i = 0; i < fireCount; i++) { | |
Rigidbody bulletInstance2 = Instantiate(bullet); | |
bulletInstance2.gameObject.SetActive(true); | |
bulletInstance2.transform.position = muzzle.position; | |
// 홀 짝 구분 | |
Vector3 angle = transform.rotation.eulerAngles + | |
(i - fireCount / 2 + (fireCount % 2 == 0 ? 0.5f : 0.0f)) * bulletAngle * Vector3.up; | |
bulletInstance2.transform.rotation = Quaternion.Euler(angle); | |
bulletInstance2.AddForce(bulletInstance2.transform.forward * bulletPower); | |
Destroy(bulletInstance2.gameObject, bulletLifeTime); | |
} | |
} | |
void FixedUpdate() | |
{ | |
if (isMoving) { | |
transform.position = Vector3.Lerp(new Vector3(transform.position.x, 0, transform.position.z), | |
targetPosition, Mathf.Clamp(speed * Time.fixedDeltaTime, 0, 1f)); | |
float sqr = Vector3.SqrMagnitude(transform.position - targetPosition); | |
if (sqr < threshold) { | |
isMoving = false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment