- Home /
How to I get my 2d gameobject to move towards another gameobject when it is clicked?
I am making a 2d puzzle game of sorts where the player has to jump from bubble to bubble. Every time they jump to a bubble, it pops, and they can no longer jump to that bubble again. However, I am having a lot of trouble with getting this main mechanic up and running. I am new to unity and I have written some code for this movement and I do not understand why it is not working. Any help is greatly appreciated :)
Bubble bubble;
// Start is called before the first frame update
void Start()
{
bubble = FindObjectOfType<Bubble>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)/*bubble.GetComponent<Bubble>().OnMouseDown()*/)
{
StopAllCoroutines();
StartCoroutine(Move(transform.position, bubble.GetComponent<Bubble>().GetBubblePosition(), speed));
}
}
IEnumerator Move(Vector2 start, Vector2 destination, float speed)
{
while((start - destination).sqrMagnitude > 0.01f)
{
transform.position = Vector2.MoveTowards(start, destination, speed * Time.deltaTime);
}
yield return null;
}
}' 'using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Bubble : MonoBehaviour {
public bool OnMouseDown()
{
return true;
}
public Vector2 GetBubblePosition()
{
return transform.position;
}
}'
Comment
use MoveTowards, there are probably 1000s of answers to this question on this site.. Just search on here.