I’m trying to make enemy ships move towards the player ship in a space shooter game while also moving from the top of the screen to the bottom of the screen and gets destroyed by a boundary which functions as it should. And I almost got how I should do it, but I can’t figure out the last details.
The relevant script code is:
public class Enemy_Controller : MonoBehavior {
private float horizontalmovement;
public float speed4;
public float speed1;
void FixedUpdate() {
horizontalmovement = EnemyShipGameObject.GetComponent<Rigidbody>().position.x -PlayerShipGameObject.GetComponent<Rigidbody>.position.x) { //this line is not correct.
if (horizontalmovement > 0) {
GetComponent<Rigidbody>().velocity = (-transform.forward*speed4*time.deltatime +transform.right*speed1*horizontalmovement*time.deltatime)*Quaternion.identity;
} else {
GetComponent<Rigidbody>().velocity = (-transform.forward*speed4*time.deltatime +transform.right*speed1*horizontalmovement*time.deltatime)*Quaternion.identity;
}
}
}
I’m sorry if the code is a little bit incorrect I have not got it to work in the relevant part of the program and I have also not got any relevant information from searching Quaternion.identity in documentation, but if I remember right it prevents the GameObjects from rotating. In the line marked “this line is not correct”. I want to make a connection between the GameObject the script is attached to with tag “EnemyShip” and the GameObject the script is not attached to with tag “Player” and use this information to get the enemy ship to move left if the player ship is currently to the left or move right if the player ship is currently to the right and keep its position if the enemy ship and the player ship is on a line, while also moving down the screen. At the same time as the player ship is constantly in motion.
I think it is only one line (the line marked “this line is not correct”) which need to be changed to one long line, and I will be very grateful if someone could tell me how this line best could be written and eventually if there are other small errors in the code. Thank you.