I am trying to practice making a space shooter in order to build on concepts for my main project, and I am having issues because I have gotten where the bullets fire and follow with the ship but they fire up and never delete from the hierarchy in Unity.
Here is the code for the Controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Transform myTransform;
public int playerSpeed = 5;
// Start is called before the first frame update
// Reusable Prefab
public GameObject BulletPrefab;
void Start()
{
myTransform = transform;
// Spawning Point
// Position x = -3, y = -3, z = -1
myTransform.position = new Vector3(-3, -3, -1);
}
// Update is called once per frame
void Update()
{
// Movement (left / right) and speed
myTransform.Translate(Vector3.right * playerSpeed * Input.GetAxis("Horizontal") * Time.deltaTime);
// Make the player wrap. If the player is at x = -10
// then it should appear at x = 10 etc.
// If it is positioned at 10, then it wraps to -10
if (myTransform.position.x > 10)
{
myTransform.position = new Vector3(-10, myTransform.position.y, myTransform.position.z);
}
else if (myTransform.position.x < -10)
{
myTransform.position = new Vector3(10, myTransform.position.y, myTransform.position.z);
}
// Space to fire!
// If the player presses space, the ship shoots.
if (Input.GetKeyDown(KeyCode.Space))
{
// Set position of the prefab
Vector3 position = new Vector3(myTransform.position.x, myTransform.position.y - 2, myTransform.position.z);
// Fire!
Instantiate(BulletPrefab, position, Quaternion.identity);
}
}
}
and here is the one for the Bullet prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public int mySpeed = 50;
private Transform myTransform;
// Start is called before the first frame update
void Start()
{
myTransform = transform;
}
// Update is called once per frame
void Update()
{
// Shooting animation
myTransform.Translate(Vector3.up * mySpeed * Time.deltaTime);
if (myTransform.position.z > 20)
{
DestroyObject(gameObject);
}
}
}
Not sure what I am doing. The bullet has gravity unchecked & is kinematic checked.
Player is positioned at -3, -1, -3.