首页 > 解决方案 > 我如何使光线投射旋转并使脚本在接触时激活

问题描述

所以我试图制作投掷和抓取脚本。

光线投射仅在右侧,我不知道如何使其旋转并在与特定对象碰撞时激活。好吧,我不确定如何改进它或让它按我想要的方式工作。我试图让它朝着你正在摆动的方向投掷,但我几乎不知道如何实现这一目标。

using UnityEngine;
using System.Collections;

public class grabberscript : MonoBehaviour
{

    public bool grabbed;
    RaycastHit2D hit;
    public float distance = 2f;
    public Transform holdpoint;
    public float throwforce;

// Use this for initialization
void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.B))
        {

            if (!grabbed)
            {
                Physics2D.queriesStartInColliders = false;

                hit = Physics2D.Raycast(transform.position, Vector2.right * transform.localScale.x, distance);

                if (hit.collider != null && hit.collider.tag == "grabbable")
                {
                    grabbed = true;

                }


                //grab
            }
            else if (!Physics2D.OverlapPoint(holdpoint.position, notgrabbed))
            {
                grabbed = false;

                if (hit.collider.gameObject.GetComponent<Rigidbody2D>() != null)
                {

                    hit.collider.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(transform.localScale.x, 1) * throwforce;
                }


                //throw
            }


        }

        if (grabbed)
            hit.collider.gameObject.transform.position = holdpoint.position;


    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.green;

        Gizmos.DrawLine(transform.position, transform.position + Vector3.right * transform.localScale.x * distance);
    }
}

标签: c#unity3d

解决方案


推荐阅读