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 :)
'using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour { [SerializeField] float speed = 10f;
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;
}
}'
Your answer
Follow this Question
Related Questions
NPC Movement 0 Answers
Issues with snake game in C# 2 Answers
unity 2d movement problem 0 Answers
How to make a 2D object, which can be moved left and right, constantly fall downwards? 1 Answer