抓钩不抓Unity中的播放器

时间:2019-03-09 16:46:05

标签: c# unity3d game-engine game-development

我正在尝试在Unity中的C#中编写抓钩。 这个想法是将一个带有标签“ Hookable”的球类游戏对象扔到一个游戏对象上,并将玩家带到抓球的地方。 可以扔出球并成功识别碰撞,但不会带球员。 该代码似乎是正确的,并且控制台没有给出任何警告,但是,我不明白发生了什么而无法正常工作。 这是代码,如果听起来有点笨拙,请对不起:

抓钩(附在玩家游戏对象上):

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

public class GrapplingHook : MonoBehaviour
{
    public GameObject hook;
    public GameObject hookHolder;

    public float hookTravelSpeed;
    public float playerTravelSpeed;

    public static  bool fired;
    public bool hooked;

    public float maxDistance;
    private float currentDistance;

    void Update()
    {
    //firing the hook
        if(/*Input.GetMouseButtonDown(0)*/Input.GetKeyDown(KeyCode.H) && fired == false)
            fired = true;

        if (fired == true && hooked == false)
        {
            hook.transform.Translate(Vector3.forward * Time.deltaTime * hookTravelSpeed);
            currentDistance = Vector3.Distance(transform.position, hook.transform.position);

            if(currentDistance >= maxDistance)
                ReturnHook();
        }

        if(hooked == true)
        {
            transform.position = Vector3.MoveTowards(transform.position,
            hook.transform.position, Time.deltaTime * playerTravelSpeed);
            float distanceToHook = Vector3.Distance(transform.position, hook.transform.position);

            if(distanceToHook < 1)
                ReturnHook();
        }
    }

    void ReturnHook()
    {
        hook.transform.position = hookHolder.transform.position;
        fired = false;
        hooked = false;
    }

}

以下是检查是否检测到抓钩的代码(附加到Hook和Hookable对象上):

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

public class HookDetector : MonoBehaviour
{
    public GameObject player;

   void OnTriggerEnter(Collider other)
   {
        if(other.tag == "Hookable")
        {
        player.GetComponent<GrapplingHook>().hooked = true;
        Debug.Log("Tocou");
        }
   }
}

1 个答案:

答案 0 :(得分:0)

问题解决了。 我将脚本附加到错误的游戏对象上,解决方法是将脚本附加到玩家GameObject上。