简体   繁体   English

unity 3d 中吊一个 object

[英]Lifting an object in Unity 3d

I am writing code for a Unity 3d game, I ran into the problem that the trigger for raising an object works every other time and does not always work.我正在为 Unity 3d 游戏编写代码,我遇到了一个问题,即引发 object 的触发器每隔一段时间工作一次,但并不总是有效。 Maybe I missed something...也许我错过了什么......

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

public class PickupC4 : MonoBehaviour
{
    public GameObject camera;
    public float distance;
    GameObject currentС4;
    bool canPickUp;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q)) OnDropEnter();
    }

    void OnTriggerEnter(Collider other)
    {
        RaycastHit hit;

        if (Physics.Raycast(camera.transform.position, camera.transform.forward, out hit, distance))
        {
            if (hit.transform.tag == "Bomb")
            {
                if (canPickUp) OnDropEnter();

                currentС4 = hit.transform.gameObject;
                currentС4.GetComponent<Rigidbody>().isKinematic = true;
                currentС4.transform.parent = transform;
                currentС4.transform.localPosition = Vector3.zero;
                currentС4.transform.localEulerAngles = new Vector3(10f, 0f, 0f);
                canPickUp = true;

            }
        }
    }


    void OnDropEnter()
    {
        currentС4.transform.parent = null;
        currentС4.GetComponent<Rigidbody>().isKinematic = false;
        canPickUp = false;
        currentС4 = null;
    }

}

I read articles on the advice, but I didn't understand anything, I count on your help.我阅读了有关建议的文章,但我什么都不懂,我希望得到您的帮助。 If there are articles that will help solve the issue, I will be glad如果有文章可以帮助解决问题,我将很高兴

Two things:两件事情:

  1. The variable canPickUp might be causing an issue.变量 canPickUp 可能会导致问题。 You only set it to true after checking to see if it is true— possibly your method for resetting canPickUp to true is failing, and therefore your code isn't executing.您只有在检查它是否为真后才将其设置为 true — 可能您将 canPickUp 重置为 true 的方法失败,因此您的代码没有执行。 Try observing canPickUp's value while testing, it may be false when it should be true.尝试在测试时观察 canPickUp 的值,它可能在应该为真时为假。

  2. You're running this code in OnTriggerEnter(), which only runs on the first frame of the collision, not every frame of the collision.您在 OnTriggerEnter() 中运行此代码,它仅在碰撞的第一帧运行,而不是在碰撞的每一帧运行。 If your raycast misses on the first frame, you've missed your chance to pick up the bomb.如果您的光线投射在第一帧未命中,您就错过了捡起炸弹的机会。 Try switching to OnTriggerStay, or using a keypress to determine when to cast the ray.尝试切换到 OnTriggerStay,或使用按键来确定何时投射光线。

Best of luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM