Unity3D 拖拽力量指示条

Kapture 2019-08-10 at 21.45.22.gif

游戏中,有时需要一个指示条来标明拖拽的力度。比如愤怒的小鸟 拖弹弓的力度,或者高尔夫游戏里挥杆的力度等等。
今天我们使用LineRenderer来实现下上面效果图中的效果。

首先在Update中侦听鼠标按下,移动,和松开三个时间

 if (Input.GetMouseButtonDown(0))
        {
           
        }
        if (Input.GetMouseButton(0))
        {
           
        }
        if (Input.GetMouseButtonUp(0))
        {
            
        }

我们这来的LineRenderer只需要两个点。设置LineRenderer的positionCount为2。
将鼠标按下时的坐标设置为起点,将鼠表按下后移动的当前位置设置为LineRender的第二个点。

鼠标按下世界坐标位置,我们可以通过 Camera.ScreenToWorldPoint来实现,默认出来的位置距离相机的Z值为0,所以上一个camOffset = new Vector3(0,0,10)。

startPos = camera.ScreenToWorldPoint(Input.mousePosition) + camOffset;

同时在Inspector中 添加一个 曲线来控制 线条的宽度,我们可以设置起点处宽一点,第二个顶点处窄一点。

 [SerializeField] AnimationCurve ac;

屏幕快照 2019-08-10 下午10.14.04.png

通过LineRenderer.numCapVertices = 10;将线条的两端设置为圆角。

完整代码如下:

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

public class DragIndicatorScript : MonoBehaviour
{

    Vector3 startPos;
    Vector3 endPos;
    Camera camera;
    LineRenderer lr;

    Vector3 camOffset = new Vector3(0, 0, 10);

    [SerializeField] AnimationCurve ac;

    // Start is called before the first frame update
    void Start()
    {
        camera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (lr == null)
            {
                lr = gameObject.AddComponent<LineRenderer>();
            }
            lr.enabled = true;
            lr.positionCount = 2;
            startPos = camera.ScreenToWorldPoint(Input.mousePosition) + camOffset;
            lr.SetPosition(0, startPos);
            lr.useWorldSpace = true;
            lr.widthCurve = ac;
            lr.numCapVertices = 10;
        }
        if (Input.GetMouseButton(0))
        {
            endPos = camera.ScreenToWorldPoint(Input.mousePosition) + camOffset;
            lr.SetPosition(1, endPos);
        }
        if (Input.GetMouseButtonUp(0))
        {
            lr.enabled = false;
        }
    }
}

更多Unity相关教程,关注微信公众号UnityAsk。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值