etc-posts/Unity :: C# 튜토리얼

[유니티C#][기초] 6.플레이어 슈팅 2

플라즈밍 2018. 7. 8. 18:18
반응형



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerShooting2 : MonoBehaviour
{
    public Transform gunBarrelEnd;
    private LineRenderer gunLine;
 
    public float power = 10000f;
    public float range = 100f;
    public float timeBetweenBullets = 0.15f;
    public float effectsDisplayTime = 0.05f;
 
    private Ray ray = new Ray();
    private RaycastHit hit;
    private float timer = 0f;
 
    public void Awake()
    {
        gunLine = GetComponentInChildren<LineRenderer>();
    }
 
    public void Update()
    {
        //틱 타이머를 사용하네 // 의존성이 큰듯
        timer += Time.deltaTime;
 
        if (Input.GetButton("Fire1"&& timer > timeBetweenBullets)
        {
            timer = 0f;
            Shoot();
        }
 
        if (timer > effectsDisplayTime)
            DisableEffects();
    }
 
    private void Shoot()
    {
        gunLine.SetPosition(0, gunBarrelEnd.position);
 
        ray.origin = gunBarrelEnd.position;
        ray.direction = gunBarrelEnd.forward;
        //레이캐스트가 성공하면 , 라인이 그려지고,Hit포인트에 콜라이더가 있으면
        //AddForce물리적 계산을 추가함.
        if (Physics.Raycast(ray, out hit, range))
        {
            gunLine.SetPosition(1, hit.point);
            if (hit.collider != null)
            {
                var rb = hit.collider.GetComponent<Rigidbody>();
                if (rb != null)
                    rb.AddForce(gunBarrelEnd.forward * power);
            }
        }
        else
        {
            var goalPosition = gunBarrelEnd.position + (gunBarrelEnd.forward * range);
            gunLine.SetPosition(1, goalPosition);
        }
 
        gunLine.enabled = true;
    }
 
    private void DisableEffects()
    {
        gunLine.enabled = false;
    }
}
 
 
cs


반응형