Unity中SpringJoint2D的获取和禁用

这篇博客介绍了如何在Unity3D中管理和使用SpringJoint2D组件。在单个SpringJoint2D的情况下,鸟(Bird)类会根据鼠标点击来调整自身位置,并限制最大距离。而在存在多个SpringJoint2D时,通过遍历所有SpringJoint2D并禁用它们,实现了对多个关节的控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单个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;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值