- Home /
Editing rotation of an Instantiated object
So I'm making a retro-inspired spaceship game where you shoot aliens to get points, pretty simple. I want to know how I can make my instantiated enemy lazers to point towards my player when they appear. Because my lazer sprite is kinda small, when they rotate the box collider2D basically dies and it doesn't appear on the screen. I've tried using a bunch of stuff but I'm probably not succeeding because I don't completely understand Quaternions. Keep in mind I've been learning Unity for a couple weeks now. This is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SingleLazerSide : MonoBehaviour
{
public Rigidbody2D rb;
public float fireSpeed;
public GameObject lazer;
//this is the lazer with this script^
public GameObject playerShip;
//I want it to point towards this
void Start()
{
rb.velocity += new Vector2 (-fireSpeed, 0f);
}
void OnBecameInvisible()
{
Destroy(this.gameObject);
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag != "alien")
{
Destroy(this.gameObject);
}
}
}
Thanks in advance
Answer by Acegikmo · Apr 28, 2020 at 08:47 PM
Something like this perhaps?
Vector2 dirToShip = (playerShip.transform.position - transform.position).normalized;
float angDeg = Mathf.Atan2(dirToShip.y, dirToShip.x) * Mathf.RadToDeg;
transform.rotation = Quaternion.Euler( 0f, 0f, angDeg );
Answer by Luis_Gan · Apr 28, 2020 at 08:52 PM
If you want the laser to look at the player try this:
void Update()
{
lazer.transform.right = playerShip.transform.position - lazer.transform.position;
}
Answer by Cassos · Apr 28, 2020 at 08:53 PM
// get direction you want to point at
Vector2 direction = (playerShip.transform.position - transform.position).normalized;
// set vector of transform directly
transform.up = direction;
Hope that works out.
Greetings,
Max