当前位置:网站首页>碰撞检测 Unity实验代码

碰撞检测 Unity实验代码

2022-06-10 14:16:00 CTGU_narcissistic_zh

CharacterCollision.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterCollision : MonoBehaviour {
	private bool doorIsOpen = false;
	private float doorTimer = 0.0f;
	public float doorOpenTime = 3.0f;
	// Use this for initialization
	void Start () {
		
	}

	void OnControllerColliderHit(ControllerColliderHit hit)
	{
		if (hit.gameObject.tag == "houseDoor" && doorIsOpen == false)
			OpenDoor ();
	}

	void OpenDoor(){
		doorIsOpen = true;
		GameObject myHouse = GameObject.Find ("house");
		myHouse.GetComponent<Animation> ().Play ("dooropen");
	}

	void ShutDoor()
	{
		doorIsOpen = false;
		GameObject myHouse = GameObject.Find ("house");
		myHouse.GetComponent<Animation> ().Play ("doorshut");
	}
	// Update is called once per frame
	void Update()
	{
		if (doorIsOpen) {
			doorTimer += Time.deltaTime;
			if (doorTimer > doorOpenTime) {
				ShutDoor ();
				doorTimer = 0.0f;
			}
		}
	}
}


RayCharacterCollision.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayCharacterCollision : MonoBehaviour {
	private bool doorIsOpen = false;
	private float doorTimer = 0.0f;
	public float doorOpenTime = 3.0f;
	// Use this for initialization
	void Start () {

	}

	void OpenDoor(){
		doorIsOpen = true;
		GameObject myHouse = GameObject.Find ("house");
		myHouse.GetComponent<Animation> ().Play ("dooropen");
	}

	void ShutDoor()
	{
		doorIsOpen = false;
		GameObject myHouse = GameObject.Find ("house");
		myHouse.GetComponent<Animation> ().Play ("doorshut");
	}
	// Update is called once per frame
	void Update()
	{
		RaycastHit hit;
		if(Physics.Raycast(transform.position,transform.forward,out hit,5)){
			if(hit.collider.gameObject.tag=="houseDoor"&&doorIsOpen==false){
				OpenDoor();
			}
		}
		if (doorIsOpen) {
			doorTimer += Time.deltaTime;
			if (doorTimer > doorOpenTime) {
				ShutDoor ();
				doorTimer = 0.0f;
			}
		}
	}
}


TriggerCollision.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerCollision : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		transform.Translate (transform.right * Input.GetAxis ("Horizontal") * Time.deltaTime, Space.Self);
	}
	void OnTriggerEnter(Collider other)
	{
		Debug.Log ("Come to triggerEnter");
		if (other.gameObject.tag == "tagSphere")
			Destroy (other.gameObject);
	}
}

原网站

版权声明
本文为[CTGU_narcissistic_zh]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zhanghanqmx/article/details/125210118