我正在尝试制作一款太空射击游戏,以便为我的主要项目建立概念,我遇到了问题,因为我已经得到了子弹射击的地方,并跟随飞船,但它们在Unity中开火并且永远不会从层次结构中删除。
下面是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);
}
}
}
,这里是子弹预制:
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);
}
}
}
不知道我在做什么。子弹的重力不受限制& &;运动检查
玩家的位置是-3,-1,-3。
为什么你的对象没有被删除可能是因为你正在检查它沿着z轴的位置,当你只是沿着y轴移动它。摧毁永远不会运行,因为你的子弹的z轴位置是静态的,总是低于20:
// Shooting animation
myTransform.Translate(Vector3.up * mySpeed * Time.deltaTime);
if (myTransform.position.z > 20)
{
DestroyObject(gameObject);
}
你可以改变if语句,让它沿着y轴检查,或者沿着z轴移动子弹,你想要哪一个,我真的不能说,因为我真的不知道你想让子弹朝哪个方向移动。
另外,我不知道它是否会引起任何问题,但是DestroyObject已经被Destroy()取代了。