博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DragRigidbody2D
阅读量:6904 次
发布时间:2019-06-27

本文共 2435 字,大约阅读时间需要 8 分钟。

组件源码

using UnityEngine;using System.Collections;//This script allows to drag rigidbody2D elements on the scene with orthographic camera//Attach this script to your camerapublic class DragRigidbody2D : MonoBehaviour{    public float Damper = 5f;    public float Frequency = 3;    public float Drag = 10f;    public float AngularDrag = 5f;        private SpringJoint2D _springJoint;    private Camera _camera;    private RaycastHit2D _rayHit;        void Start ()        {        _camera = gameObject.GetComponent
(); } void Update () { if (!Input.GetMouseButtonDown(0)) return; //Looking for any collider2D under mouse position _rayHit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); if (_rayHit.collider == null) return; if (!_rayHit.collider.rigidbody2D || _rayHit.collider.rigidbody2D.isKinematic) return; if (!_springJoint) { //Create spring joint GameObject go = new GameObject("[Rigidbody2D_dragger]"); Rigidbody2D body = go.AddComponent
(); _springJoint = go.AddComponent
(); body.isKinematic = true; } _springJoint.transform.position = _rayHit.point; _springJoint.anchor = Vector2.zero; //Apply parameters to spring joint _springJoint.frequency = Frequency; _springJoint.dampingRatio = Damper; _springJoint.distance = 0; _springJoint.connectedBody = _rayHit.collider.rigidbody2D; StartCoroutine("DragObject"); } IEnumerator DragObject() { var oldDrag = _springJoint.connectedBody.drag; var oldAngDrag = _springJoint.connectedBody.angularDrag; _springJoint.connectedBody.drag = Drag; _springJoint.connectedBody.angularDrag = AngularDrag; while (Input.GetMouseButton(0)) { Vector2 newPos = _camera.ScreenToWorldPoint(Input.mousePosition); _springJoint.transform.position = new Vector2(newPos.x, newPos.y); yield return new WaitForSeconds(0.1f); } if (_springJoint.connectedBody) { _springJoint.connectedBody.drag = oldDrag; _springJoint.connectedBody.angularDrag = oldAngDrag; _springJoint.connectedBody = null; } }}

使用方法

Drag预览

转载地址:http://tzldl.baihongyu.com/

你可能感兴趣的文章
《 Java并发编程从入门到精通》 Java线程池的监控
查看>>
《Ansible权威指南》一1.8 Python多环境扩展管理
查看>>
《全栈性能测试修炼宝典 JMeter实战》—第1章 1.5节从招聘要求看岗位价值
查看>>
Gartner2017年十大技术趋势
查看>>
sum() 函数性能堪忧,列表降维有何良方?
查看>>
fastreport 导出图片并打印
查看>>
学习html我们从百度百科开始
查看>>
如何Spring Cloud Zuul作为网关的分布式系统中整合Swagger文档在同一个页面上
查看>>
实现一个炫酷的随机标签排列效果(颜色随机,大小随机,成菱形排列的列表)...
查看>>
flex 布局
查看>>
数字资产交易所开发:平台币快速吸金的背后
查看>>
小程序自定义音频组件,带滚动条,IOS循环失效问题
查看>>
Swift开发之粒子动画的实现
查看>>
我学Java我傲娇
查看>>
挖矿蠕虫肆虐,详解云防火墙如何轻松“制敌”
查看>>
Linux -- Samba之客户端访问(Linux和windows)
查看>>
八个Docker的真实应用场景
查看>>
vpc的使用方法
查看>>
GitExtensions GitCredentialWinStore syntax error near unexpected token `('
查看>>
Java获取EXE文件图标的方法
查看>>