I’m currently working on a 2D project and I have a scene where I generate a random point within the bounds of the screen and move a game object to that point at a speed(soon to make the speed random). I have it repeat once the game object hits the point to generate another random point and move to it. But the second point the game object typically flies off almost on a tangent to its path and the next path. Any help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrackingBall : MonoBehaviour
{
Vector2 topright = new Vector2(1, 1);
Vector2 bounds;
Vector2 nextPos;
public float speed;
public GameObject collider;
void Start()
{
bounds = Camera.main.ViewportToWorldPoint(topright);
ChangeDirection();
}
void OnTriggerEnter2D(Collider2D coll) {
if (coll.transform.tag == "Collider"){
ChangeDirection();
}
}
public void ChangeDirection() {
nextPos = new Vector2(Random.Range(-bounds.x + 1.5f, bounds.x - 1.5f), Random.Range(-bounds.y + 1.5f, bounds.y - 1.5f));
collider.transform.position = nextPos;
Debug.DrawLine(gameObject.transform.position, nextPos, Color.red, 10f);
GetComponent<Rigidbody2D>().velocity = (Vector2)gameObject.transform.position + nextPos * speed;
Debug.DrawLine(gameObject.transform.position, (Vector2)gameObject.transform.position + nextPos * speed, Color.green, 10f);
}
}