c# - 如何制作具有 Action 范围的开/关门?

标签 c# unity3d scripting

我想制作一扇通过按下按钮打开和关闭的门(“O”表示打开,“C”表示关闭)。试过这个:

using System.Collections;
using UnityEngine;
public class DoorScript : MonoBehaviour {

public float speed;
public float angle;
public Vector3 direction;
    // use this for initializaton
    void start() {
        angle = transform.eulerAngles.y;
    }

    // Update is called once per frame
    void Update() {
        if (Mathf.Round(transform.eulerAngles.y) != angle) {
            //rotate our door
            transform.Rotate(direction * speed);
        }

        if (Input.GetKeyDown(KeyCode.O)) {
            angle = 90;
            direction = Vector3.up;
        } 

        if (Input.GetKeyDown(KeyCode.C)) {
            angle = 0;
            direction = -Vector3.up;
     }
   }
}

但它并没有按照我想要的方式工作。我的意思是:你可以在很远的地方,如果你按“O”,门就会打开。我如何实现行动范围?我的意思是,你需要离门更近一点才能与之互动吗? 我还需要说的是,在游戏中我会很接近。 40门。我需要为彼此定制脚本吗?

代码在 C# 中。我有一点编码经验,但我无法解决这个问题。

谢谢

最佳答案

执行此操作的一种方法是使用 Colliders、RigidBodies 和 OnTrigger 调用。这是概述用法的手册页。

https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html

对于您的实现,门将具有示例脚本(将其称为“示例”以外的名称),玩家将是球体(尽管您将在该脚本之外创建玩家)。当玩家靠近一扇门时,门会通过 OnTrigger 调用跟踪玩家的存在,从而知道这一点。然后,当按下 key 时,如果用户在附近,门就会使用react。每扇门都会有这样的脚本。

关于c# - 如何制作具有 Action 范围的开/关门?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59219939/

相关文章:

linux - 使用带有 --parseopt 的 git rev-parse 访问 shell 脚本中的命名参数

python - 使用 Python 脚本从 Plone 检索对象的内容

c# - 这种设计模式叫什么?

C# 反射 : Replace a referenced assembly

c# - WinForms中常见的 "Drag and Drop"图标如何实现

c# - 如何使用 SimpleJSON 显示来自 json 的数据?

python - 为什么使用全局解释器锁?

C# .Net3.5 将数据添加到 SQL Server 2005 数据库(如果它尚不存在并且是否更新它)?

unity3d - Unity3D 中的简单矩形

c# - 通过 Unity Mono 将 SSL 证书安装到 Android 设备上