Home > Net >  Lifting an object in Unity 3d
Lifting an object in Unity 3d

Time:11-27

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. 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

CodePudding user response:

Two things:

  1. The variable canPickUp might be causing an issue. 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. Try observing canPickUp's value while testing, it may be false when it should be true.

  2. You're running this code in OnTriggerEnter(), which only runs on the first frame of the collision, not every frame of the collision. 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.

Best of luck.

  • Related