|
상속과 오버라이드 virtual, override
base.start();
변수의 접근제한 protected
interface
IDamageable.cs
- using UnityEngine;
- public interface IDamageable {
- void TakeHit(float damage, RaycastHit hit);
- }
LivingEntity.cs
- using UnityEngine;
- using System.Collections;
- public class LivingEntity : MonoBehaviour, IDamageable {
- public float startingHealth;
- protected float health;
- protected bool dead;
- protected virtual void Start()
- {
- health = startingHealth;
- }
- public void TakeHit(float damage, RaycastHit hit)
- {
- health -= damage;
- if(health <=0 && !dead)
- {
- Die();
- }
- }
- protected void Die()
- {
- dead = true;
- GameObject.Destroy(gameObject);
- }
- }
Player.cs
- using UnityEngine; using System.Collections;
- [RequireComponent (typeof (PlayerController))]
- [RequireComponent(typeof(GunController))]
- public class Player : LivingEntity {
- public float moveSpeed = 5;
- PlayerController controller;
- GunController gunController;
- Camera viewCamera;
- protected override void Start () {
- base.Start();
- controller = GetComponent();
- gunController = GetComponent();
- viewCamera = Camera.main;
- }
- void Update ()
- {
- //movement input
- Vector3 moveInput = new Vector3(Input.GetAxisRaw("Horizontal"),
- 0, Input.GetAxisRaw("Vertical"));
- Vector3 moveVelocity = moveInput.normalized * moveSpeed;
- controller.Move(moveVelocity);
- //look input
- Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
- Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
- float rayDistance;
- if (groundPlane.Raycast(ray,out rayDistance))
- {
- Vector3 point = ray.GetPoint(rayDistance);
- //Debug.DrawLine(ray.origin, point, Color.red);
- controller.LookAt(point);
- }
- //weapon input
- if (Input.GetMouseButton(0))
- {
- gunController.Shoot();
- }
- }
- }
Enemy.cs
- using UnityEngine;
- using System.Collections;
- [RequireComponent (typeof (NavMeshAgent))]
- public class Enemy : LivingEntity
- {
- NavMeshAgent pathfinder;
- Transform playertargeting;
- protected override void Start () {
- base.Start();
- pathfinder = GetComponent();
- playertargeting = GameObject.FindWithTag("Player").GetComponent();
- StartCoroutine(UpdatePath());
- }
- void Update () {
- }
- IEnumerator UpdatePath()
- {
- float refreshRate = 0.25f;
- while (playertargeting != null)
- {
- Vector3 targetPosition = new Vector3(playertargeting.position.x, 0,
- playertargeting.position.z);
- if(!dead)
- {
- pathfinder.SetDestination(targetPosition);
- }
- yield return new WaitForSeconds(refreshRate);
- }
- }
- }
반응형
'응용프로그램 > 유니티(Unity)' 카테고리의 다른 글
unity - 대칭함수을 활용한 공격 (0) | 2016.11.16 |
---|---|
Unity - 스폰 시스템 만들기 (0) | 2016.11.14 |
Unity - 충돌감지관련 (0) | 2016.11.14 |
Unity - CapsuleCollider 사이의 거리알아보기. (0) | 2016.11.13 |
유니티 DB 사용하기 (0) | 2016.11.13 |