I've used a simple Unity tutorial to make a Space Invaders game, but I want to adapt it into a different game.
The tutorial made a right-and-left control of the player ship, but I changed it to rotational control (which took a while because for some reason almost no script correctly confined the rotation to the boundaries I've set).
After scripting the rotation, I wanted the shots to move forward on the screen in the direction of the axis to which it is spawned. The axis is of an empty child object inside the ship object, so its own angles are always set to 0.
I saw the original function controlling the bullet movement:
bullet.position += Vector3.up * speed;
still moves it up the screen regardless of how the bullet is rotated. So I tried:
bullet.position += Vector3.forward * speed;
and saw it moves the bullet into the Z axis.
Basically I'm asking is whether there's a sub-function of Vector3 I'm missing which moves an object according to the direction of its own axis?
Here are the codes of the two classes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShotSpawner : MonoBehaviour
{
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
private Transform bullet;
public float speed;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Transform>();
}
void FixedUpdate()
{
bullet.position += Vector3.up * speed;
if (bullet.position.y >= 10)
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
Destroy(other.gameObject);
Destroy(gameObject);
PlayerScore.playerScore++;
}
else if (other.tag == "Base")
Destroy(gameObject);
}
}