Spring Joint 2D(可能)导致 transform.position 错误
Posted
技术标签:
【中文标题】Spring Joint 2D(可能)导致 transform.position 错误【英文标题】:Spring Joint 2D (maybe) causing transform.position errors 【发布时间】:2020-06-20 13:18:33 【问题描述】:在您看到问题所在后,我知道标题可能会产生误导,但我真的不知道如何命名这个问题。 第一张图显示问题。
白线表示玩家与名为 hook 的游戏对象之间的距离。靠近钩子的蓝色精灵球体是 SpringJoint2D.connectedBody。
它们(白线和蓝色精灵)都使用相同的值:hook.transform.position。
这是我认为引起问题或至少揭示最多的代码 sn-ps:
SpringJoint2D sn-p:
if (Input.GetMouseButtonDown(0))
hook = FindClosestObject(radius, "Hook");
if(hook != null)
joint.enabled = true;
joint.connectedBody = hook;
joint.connectedAnchor = hook.transform.position;
Debug.Log("Click.");
Debug.Log(hook);
if (Input.GetMouseButtonUp(0))
joint.enabled = false;
joint.connectedBody = null;
Debug.DrawLine sn-p:
if (hook != null)
joint.distance = Vector3.Distance(hook.transform.position, transform.position) / 2;
Debug.DrawLine(transform.position, hook.transform.position);
这是完整的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
public float radius;
private SpringJoint2D joint;
private Rigidbody2D hook = new Rigidbody2D();
// Start is called before the first frame update
void Start()
joint = GetComponent<SpringJoint2D>();
// Update is called once per frame
void Update()
//touch.phase == TouchPhase.Began
if (Input.GetMouseButtonDown(0))
hook = FindClosestObject(radius, "Hook");
if(hook != null)
joint.enabled = true;
joint.connectedBody = hook;
joint.connectedAnchor = hook.transform.position;
Debug.Log("Click.");
Debug.Log(hook);
if (Input.GetMouseButtonUp(0))
joint.enabled = false;
joint.connectedBody = null;
//foreach (Touch touch in Input.touches)
//
//
if (hook != null)
joint.distance = Vector3.Distance(hook.transform.position, transform.position) / 2;
Debug.DrawLine(transform.position, hook.transform.position);
private void OnDrawGizmos()
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, radius);
if (hook != null)
Gizmos.DrawLine(transform.position, hook.transform.position);
public Rigidbody2D FindClosestObject(float radius, string tag)
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag(tag);
Rigidbody2D closest = null;
float distance = radius;
Vector3 position = transform.position;
foreach (GameObject go in gos)
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
closest = go.GetComponent<Rigidbody2D>();
distance = curDistance;
return closest;
【问题讨论】:
【参考方案1】:啊,我只是愚蠢。
如果您还分配了 connectedRigidbody2D,则无需分配 connectedAnchor connectedAnchor 是相对于 connectedRigidbody2D 位置的偏移量...
【讨论】:
以上是关于Spring Joint 2D(可能)导致 transform.position 错误的主要内容,如果未能解决你的问题,请参考以下文章
论文笔记之:Collaborative Deep Reinforcement Learning for Joint Object Search
将 `emmeans::joint_tests()` 输出中的 p 值格式保留在针织 pdf 中
如果应用程序无法启动,是不是有可能导致快速 Spring 测试失败?
Joint Neural Architecture and Hyperparameter Search for Correlated Time Series Forecasting