- Home /
Question by
latsushi · Oct 18, 2018 at 12:12 AM ·
ontriggerentermovetowards
Using MoveTowards In The Correct Method
Here's my problem... I'm trying to have coins move to a specific position in the top left when a ball passes through them. I tried setting the conditional using an if statement. However, because my code is in an 'OnTriggerEnter2D' method the coins only move when the collider of the ball is touching the colliders of the coins. I don't know what to do. Please help.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moveTowards : MonoBehaviour {
public Vector2 aPosition1 = new Vector2(-7, 4);
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Ball")
{
transform.position = Vector2.MoveTowards(new Vector2(transform.position.x, transform.position.y), aPosition1, 9 * Time.deltaTime);
Debug.Log("DID WE BUMP?");
}
}
}
Comment
I don't quite get it, so you are trying to move the coins after the ball hit them? if that's the case you could try with On TriggerExit, the coins will never move unless you hit them with something because you are using a Trigger/Collider event, you need to collide something with something to produce a reaction,
Best Answer
Answer by zamtrush · Oct 18, 2018 at 12:39 PM
public class moveTowards : MonoBehaviour {
public bool move = false;
public Vector2 aPosition1 = new Vector2(-7, 4);
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Ball")
{
move = true;
Debug.Log("DID WE BUMP?");
}
}
void Update()
{
if(move) {
transform.position = Vector2.MoveTowards(transform.position, aPosition1, 9 * Time.deltaTime);
}
}
}
Your answer