单个SpringJoint2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird : MonoBehaviour
{
private bool IsClick;
public Transform RightPos;
public float MaxDis;
private SpringJoint2D sp;
// Start is called before the first frame update
private void Awake()
//Awake()在对象实例化时调用的
//Start()在对象第一帧时调用的,且在Update()之前。
{
sps = GetComponents<SpringJoint2D>();
}
private void OnMouseDown()
{
IsClick = true;
}
private void OnMouseUp()
{
IsClick = false;
sp.enabled = false;
}
// Update is called once per frame
private void Update()
{
if (IsClick == true)
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position -= new Vector3(0, 0,Camera.main.transform.position.z);
if (Vector3.Distance(RightPos.position,transform.position) > MaxDis)
{
Vector3 Pos = (transform.position - RightPos.position).normalized;
Pos = Pos * MaxDis;
transform.position = Pos + RightPos.position;
}
}
}
}
当存在多个SpringJoint2D时
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird : MonoBehaviour
{
private bool IsClick;
public Transform RightPos;
public float MaxDis;
private SpringJoint2D sp;
private Component[] sps;
// Start is called before the first frame update
private void Awake()
{
sps = GetComponents<SpringJoint2D>();
}
private void OnMouseDown()
{
IsClick = true;
}
private void OnMouseUp()
{
IsClick = false;
foreach(SpringJoint2D sp in sps)
{
sp.enabled = false;
}
}
// Update is called once per frame
private void Update()
{
if (IsClick == true)
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position -= new Vector3(0, 0,Camera.main.transform.position.z);
if (Vector3.Distance(RightPos.position,transform.position) > MaxDis)
{
Vector3 Pos = (transform.position - RightPos.position).normalized;
Pos = Pos * MaxDis;
transform.position = Pos + RightPos.position;
}
}
}
}