본문 바로가기
IT/유니티

유니티 게임 프로그래밍 16장 예제 구현

by nutrient 2021. 5. 30.
728x90
728x170

 

 

BeetleControl

using UnityEngine;
using System.Collections;

public class BeetleControl : MonoBehaviour {

	public Vector3 targetPos = Vector3.zero;
	public float MoveSpeed = 5.0f;
	public GameObject HitEffect;
	public GameObject DeadEffect;
	public int HP  = 300;
	
	public enum BeetleState
	{
		IDLE = 0,
		WALK = 1,
		ATTACK = 2,
		HIT = 3,
		SIZE
	}
	private BeetleState state = BeetleState.IDLE;
	
	// Use this for initialization
	void Start () {
		animation.wrapMode = WrapMode.Loop;
		animation.Play("move");
		HP = 300;
	}
	
	// Update is called once per frame
	void Update () {
		SearchTarget();
		
		Vector3 currentPos = transform.position;
		Vector3 diffPos = targetPos - currentPos;
		
		if(diffPos.magnitude < 2.0f)
		{
			return;
		}
		
		diffPos = diffPos.normalized;
		
		transform.Translate(diffPos * Time.deltaTime * MoveSpeed,
		                    Space.World);
		
		transform.LookAt(targetPos);
	}
	
	void SearchTarget()
	{
		GameObject target = GameObject.FindWithTag("Player");
		targetPos = target.transform.position;
		
	}
	
	void OnTriggerEnter(Collider other)
	{
		if(other.gameObject.tag == "sword")
		{
			state = BeetleState.HIT;
			Instantiate(HitEffect,other.transform.position,
			            transform.rotation);
			CheckDead(Random.Range(10,50));
		}
	}
	void CheckDead(int damage)
	{
		GameObject dmgObj = Instantiate(Resources.Load("Prefabs/DamageText"),Vector3.zero,Quaternion.identity) as GameObject;
		dmgObj.SendMessage("SetText",damage.ToString());
		dmgObj.SendMessage("SetTarget",gameObject);
		dmgObj.SendMessage("SetColor",new Color(Random.Range(0.0f,1.0f),Random.Range(0.0f,1.0f),Random.Range(0.0f,1.0f)));
		HP -= damage;
		Debug.Log("HP :"+HP.ToString());
		if(HP <= 0)
		{
			Instantiate(DeadEffect, transform.position,transform.rotation);
			Destroy(gameObject);
		}
	}

}

 

BillboardAndMoveUp

using UnityEngine;
using System.Collections;

public class BillboardAndMoveUp : MonoBehaviour {

	private TextMesh textmesh;
	public float UpSpeed = 1.0f;
	public Color color = Color.yellow;
	public GameObject target_;
	
	// Use this for initialization
	void Start () {
		textmesh = gameObject.GetComponent<TextMesh>();
	}
	
	// Update is called once per frame
	void Update () {
		
		if (target_ != null) {
			transform.Translate(Vector3.up * UpSpeed * Time.deltaTime);
		}
		
		transform.LookAt(Camera.main.transform.position);
		transform.Rotate(new Vector3(0.0f,180.0f,0.0f));
		
	}
	
	public void SetText(string str)
	{
		if(textmesh == null)
		{
			textmesh = gameObject.GetComponent<TextMesh>();
		}
		
		textmesh.text = str;
	}
	
	public void SetTarget(GameObject target)
	{
		target_ = target;
		transform.position = target.transform.position;
	}
	
	public void SetColor(Color c)
	{
		color = c;
		textmesh.renderer.material.color = c;
	}
}

 

CameraControl

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour {

	//third viwe point var
	public float distance = 10.0f;
	public float height = 5.0f;
	
	public float heightDamping = 2.0f;
	public float rotationDamping = 3.0f;
	
	public GameObject target; //player
	
	public enum CameraViewPoint {FIRST = 0,SECOND = 1,THIRD = 2,SIZE}
	public CameraViewPoint current = CameraViewPoint.THIRD;
	
	void LateUpdate()
	{
		switch(current)
		{
		case CameraViewPoint.THIRD:
			ThirdView();
			break;
		case CameraViewPoint.SECOND:
			break;
		case CameraViewPoint.FIRST:
			break;
		}
	}
	void ThirdView()
	{
		if(target == null)
		{
			target = GameObject.FindWithTag("Player");
		}else
		{
			float wantedRotationAngle = target.transform.eulerAngles.y;
			float wantedHeight = target.transform.position.y+height;
			
			float currentRotationAngle = transform.eulerAngles.y;
			float currentHeight = transform.position.y;
			
			currentRotationAngle = Mathf.LerpAngle(currentRotationAngle,
			                                       wantedRotationAngle,rotationDamping * Time.deltaTime);
			currentHeight = Mathf.Lerp(currentHeight,wantedHeight,
			                           heightDamping * Time.deltaTime);
			
			Quaternion currentRotation = Quaternion.Euler(0,
			                                              currentRotationAngle,0);
			
			//player position
			transform.position = target.transform.position; 
			// move back
			transform.position -= currentRotation * Vector3.forward * distance;
			
			transform.position = new Vector3(transform.position.x,
			                                 currentHeight,
			                                 transform.position.z);
			transform.LookAt(target.transform);
			
		}
	}
}

 

DelayAndDestroy

using UnityEngine;
using System.Collections;

public class DelayAndDestroy : MonoBehaviour {

	public float delayTime =  0.0f;
	public float destroyTime = 1.0f;
	private float createTime;
	// Use this for initialization
	void Start () {
		createTime = Time.time;
		RenderOnOFF(false);
	}
	// Update is called once per frame
	void Update () {
		if( createTime + delayTime < Time.time )
		{
			RenderOnOFF( true );
		}
		if( createTime + delayTime + destroyTime < Time.time )
		{
			Destroy(gameObject);
		}
		
	}
	void RenderOnOFF( bool onoff )
	{
		MeshRenderer[] render = GetComponentsInChildren<MeshRenderer>();
		foreach( MeshRenderer ren in render)
		{
			ren.enabled = onoff;
		}
	}
}

 

PlayerControl

using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {

	public float MoveSpeed = 5.0f;
	public float RotateSpeed = 500.0f;
	public float VerticalSpeed = 0.0f;
	private float gravity = 9.8f;
	
	private CharacterController charactercontroller;
	
	private Vector3 MoveDirection = Vector3.zero;
	private CollisionFlags collisionflags;
	
	public AnimationClip idleAnim;
	public AnimationClip walkAnim;
	public AnimationClip attackAnim;
	public AnimationClip skillAnim;
	public enum CharacterState
	{
		IDLE = 0,
		WALK = 1,
		ATTACK = 2,
		SKILL = 3,
		SIZE
	}
	private CharacterState state = CharacterState.IDLE;	
	
	// Use this for initialization
	void Start () {
		charactercontroller = GetComponent<CharacterController>();
		
		animation.wrapMode = WrapMode.Loop;
		animation.Stop();
		
		animation[attackAnim.name].wrapMode = WrapMode.Once;
		animation[attackAnim.name].layer = 1;

		animation[skillAnim.name].wrapMode = WrapMode.Once;
		animation[skillAnim.name].layer = 1;

		
	}
	
	// Update is called once per frame
	void Update () {
		Move ();
		CheckState();
		AnimationControl();
		BodyDirection();
		ApplyGravity();
	}

	void ApplyGravity()
	{
		if(charactercontroller.isGrounded == true)
		{
			VerticalSpeed = 0.0f;
		}else
		{
			//on air
			VerticalSpeed -= gravity * Time.deltaTime;
		}
	}
	
	void BodyDirection()
	{
		Vector3 horizontalVelocity = charactercontroller.velocity;
		horizontalVelocity.y = 0.0f;
		if(horizontalVelocity.magnitude > 0.0f)
		{
			Vector3 trans = horizontalVelocity.normalized;
			Vector3 wantedVector = Vector3.Lerp(transform.forward,
			                                    trans,0.5f);
			if(wantedVector != Vector3.zero)
			{
				transform.forward = wantedVector;
			}
		}
	}

	void AnimationControl()
	{
		switch(state)
		{
		case CharacterState.IDLE:
			animation.CrossFade(idleAnim.name);
			break;
		case CharacterState.WALK:
			animation.CrossFade(walkAnim.name);
			break;
		case CharacterState.ATTACK:
			if(animation[attackAnim.name].normalizedTime > 0.9f)
			{
				animation[attackAnim.name].normalizedTime = 0.0f;
				state = CharacterState.IDLE;
			}else
			{
				animation.CrossFade(attackAnim.name);
			}
			break;
		case CharacterState.SKILL:
			if(animation[skillAnim.name].normalizedTime > 0.9f)
			{
				animation[skillAnim.name].normalizedTime = 0.0f;
				state = CharacterState.IDLE;
			}else
			{
				animation.CrossFade(skillAnim.name);
			}
			break;
		}

	}
	
	void CheckState()
	{
		if(state == CharacterState.ATTACK||state == CharacterState.SKILL) 
		{
			return;
		}
		
		if(charactercontroller.velocity.sqrMagnitude > 0.1f)
		{
			//move
			state = CharacterState.WALK;
		}else
		{
			//stand
			state = CharacterState.IDLE;
		}
		if(Input.GetMouseButtonDown(0))
		{
			state = CharacterState.ATTACK;
		}
		if(Input.GetMouseButtonDown(1))
		{
			state = CharacterState.SKILL;
		}

	}
	
	void Move()
	{
		Transform cameraTransform = Camera.mainCamera.transform;
		
		Vector3 forward = cameraTransform.
			TransformDirection(Vector3.forward);
		forward = forward.normalized; //normal vector 1 vector
		Vector3 right = new Vector3(forward.z ,0.0f,-forward.x);
		
		float v = Input.GetAxisRaw("Vertical");
		float h = Input.GetAxisRaw("Horizontal");
		
		Vector3 targetVector = v *forward + h * right;
		targetVector = targetVector.normalized; //normal vector
		
		MoveDirection = Vector3.RotateTowards(MoveDirection,
		                                      targetVector,RotateSpeed*Mathf.Deg2Rad*Time.deltaTime
		                                      ,500.0f);
		MoveDirection = MoveDirection.normalized;
		
		Vector3 grav = new Vector3(0.0f,VerticalSpeed,0.0f);
		
		Vector3 movementAmt = (MoveDirection * MoveSpeed * 
		                       Time.deltaTime)+grav;
		collisionflags = charactercontroller.Move(movementAmt);
		
	}
}

 

SpawnerControl

using UnityEngine;
using System.Collections;

public class SpawnerControl : MonoBehaviour {

	public float SpawnTime = 1.0f;
	public float LastSpawnTime;
	public GameObject monster;
	
	// Use this for initialization
	void Start () {
		LastSpawnTime = Time.time;
	}
	
	// Update is called once per frame
	void Update () {
		if(Time.time > LastSpawnTime + SpawnTime)
		{
			LastSpawnTime = Time.time;
			Vector3 pos = new Vector3(
				transform.position.x + Random.Range(-5.0f,5.0f),
				transform.position.y,
				transform.position.z + Random.Range(-5.0f,5.0f));
			
			Instantiate(monster,pos,transform.rotation);
		}
	}
}

 

 

728x90
그리드형

댓글