0

按照教程,我正在尝试使用使用弹簧接头和 Line Renderer 的抓斗枪技工。

我在鼠标点击时画了线,但线的末端没有在用户点击的地方画。

它看起来像这样:

任何人都可以帮助我解决为什么它不起作用?这是正在实施的(古怪的)项目 - https://i.imgur.com/IuMsEsQ.mp4

抓斗枪代码:

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

public class GrapplingGun : MonoBehaviour
{
    private LineRenderer lr;
    private Vector3 grapplePoint; //where we grapple to
    public LayerMask whatIsGrappable;
    public Transform gunTip;
    public Transform cam;
    public Transform player;
    private float maxDistance = 100f;
    private SpringJoint joint;

    void Awake()
    {
        lr = GetComponent<LineRenderer>();
    }

    void Update()
    {


        if (Input.GetMouseButtonDown(0))
        {
            StartGrapple();
        }
        else if (Input.GetMouseButtonUp(0))
        {
            StopGrapple();
        }
    }

    void LateUpdate()
    {
        DrawRope();
    }

    void StartGrapple()
    {
        RaycastHit hit;
        if (Physics.Raycast(cam.position, cam.forward, out hit, maxDistance, whatIsGrappable))
        //if (Physics.Raycast(transform.position, Vector3.forward, out hit, maxDistance, whatIsGrappable))
        {
            grapplePoint = hit.point;
            joint = player.gameObject.AddComponent<SpringJoint>();
            joint.autoConfigureConnectedAnchor = false;
            joint.connectedAnchor = grapplePoint;

            float distanceFromPoint = Vector3.Distance(player.position, grapplePoint);
            joint.maxDistance = distanceFromPoint * 0.8f;
            joint.minDistance = distanceFromPoint * 0.25f;

            joint.spring = 4.5f;
            joint.damper = 7f;
            joint.massScale = 4.5f;

            lr.positionCount = 2;
        }

    }

    void DrawRope()
    {
        //If not grappling, don't draw anything
        if (!joint) return;

        lr.SetPosition(0, gunTip.position);
        lr.SetPosition(1, grapplePoint);
    }
    void StopGrapple()
    {
        lr.positionCount = 0;
        Destroy(joint);
    }
}

谢谢你。

4

1 回答 1

1

根本问题是您的光线投射。第二个参数是射线的方向,您将其作为相机方向。因此,目前您的光线始终从相机指向前方。

您可以做的是使用Camera.ScreenPointToRay提供要投射的光线,以便为您提供要投射到的 3d 鼠标位置,然后使用当前的光线投射,但将第二个参数替换为从玩家到光线投射命中点的方向从前面提到的功能

Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit hit);
if (Physics.Raycast(transform.position, (hit.point - transform.position).normalized, out hit, maxDistance, whatIsGrappable)) {
    // Your code here...
}
于 2020-05-16T09:14:36.577 回答