1
\$\begingroup\$

What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it.

The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node.

What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing.

Here is all of my code:

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

public class Object_Moveable: MonoBehaviour {


 private Vector2 mousePos;
 public float moveSpeed;
 public float offset = 0f;
 private bool following;
 private GameObject SelectedNode;

 // Use this for initialization
 void Start() {
  following = false;
  offset += 10;
 }


 void Update() {

  if (Input.GetMouseButtonDown(0) && ((Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).magnitude <= offset)) {
   following = true;
  }

  if (following) {
   transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed);
  }


  if (Input.GetMouseButtonUp(0)) {
   following = false;
   //Attach (Node, 0, 0);
   transform.localPosition = SelectedNode.transform.position;
  }
 }

 void OnTriggerEnter2D(Collider2D trigger) {
  if (trigger.tag == "pipenode") {
   transform.SetParent(trigger.transform);
   SelectedNode = trigger.gameObject;
  }
 }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Well, the center of the parent object would be the local position of (0,0,0)... \$\endgroup\$ Commented Mar 5, 2018 at 20:16

1 Answer 1

2
\$\begingroup\$

Your local position is the position relative to the parent.

This means that to put an object exactly on the parent, it's local position must be (0, 0, 0) (meaning no change compared to the parent).

In your case, do

transform.localPosition = Vector3.zero;
\$\endgroup\$
1
  • \$\begingroup\$ This ended up being very close to the actual solution. I had to make several changes to the code as a whole, and used something very similar. \$\endgroup\$ Commented Apr 18, 2018 at 0:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .