Hi!
Been working on my first game on Unity which is a simple asteroid shooting game. Currently been adding power-ups to my game and wanted to to add one which guides the beam (aka. the bullet) to the closest asteroid. How I’ve implemented it so far is that the beam will continue to shoot straight where the player has aimed until the child object, an empty object with a large collider (as trigger) in front, collides with an asteroid which then becomes the beam’s target.
Unfortunately, I can’t seem to get the thing working as the beam seems to just continue straight and doesn’t track the asteroid at all!
Here is the script for the beam:
public class BeamController : MonoBehaviour
{
public Rigidbody2D rb;
protected float speed = 20f;
private float rotateSpeed = 200f;
public GameObject impactEffect;
public bool isTargetMode;
private Transform target;
public GameObject Player;
// Start is called before the first frame update
void Start ()
{
rb.velocity = transform.right * speed;
Player = GameObject.FindWithTag("Player");
PlayerController controller = Player.GetComponent<PlayerController>();
if(controller.isBeamTargeted == true)
{
isTargetMode = true;
}
}
public void targetFound(Transform newTarget)
{
if(target == null)
{
target = newTarget;
}
}
void FixedUpdate()
{
if(isTargetMode && target != null)
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize ();
float rotateAmount = Vector3.Cross (direction, transform.right).z;
rb.angularVelocity = -rotateSpeed * rotateAmount;
rb.velocity = transform.right * speed;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
GameObject impact = Instantiate(impactEffect, collision.contacts[0].point, Quaternion.identity);
Destroy(impact, 0.1f);
Destroy(gameObject);
}
}