- 在角色控制器上创建脚本:
关键字:out,表示输出该对象;
光线投射到的场景上,需要将它的标签设置为:"playDoor"与脚本中的一致即可;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class playercollisions : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
//光线投射,这里的10表示距离,即门和光源的距离
if (Physics.Raycast(transform.position, transform.forward, out hit, 10)){
if (hit.collider.gameObject.tag == "playDoor") {
GameObject currentdoor = hit.collider.gameObject;
currentdoor.SendMessage("doorcheck");
}
}
}
}
- 作用场景中门:创建脚本:
这里两个音乐文件为同一个,在脚本中设置好,播放动画是通过父控制件来进行播放的;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class doorManager : MonoBehaviour
{
// Start is called before the first frame update
private bool doorisopen = false;
private float doortime = 0.0f;
private GameObject currentdoor;
private int number = 0;
public float door_open_time = 3.0f;
public AudioClip door_open_sound;
public AudioClip door_close_sound;
public AudioSource audioPlayer;
void Start()
{
audioPlayer = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
//计时操作
if (doorisopen)
{
doortime += Time.deltaTime;
}
if (doortime > door_open_time)
{
closeDoor();
doorisopen = false;
doortime = 0;
//关门
}
}
void doorcheck() {
//门没有关
if (!doorisopen) {
opendoor();
}
}
void opendoor() {
audioPlayer.clip = door_open_sound;
audioPlayer.Play();
transform.parent.GetComponent<Animation>().Play("dooropen");
doorisopen = true;
}
void closeDoor()
{
audioPlayer.clip = door_close_sound;
audioPlayer.Play();
transform.parent.GetComponent<Animation>().Play("doorclose");
}
}