我正在从以下网站复制项目: http://blog.lessmilk.com/unity-spaceshooter-1/ http://blog.lessmilk.com/unity-spaceshooter-2/
但是,当按下空格键时,我的子弹不会向前移动。以下是我的脚本:
spaceshipScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spaceshipScript : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start () {
}
void Update() {
// Get the rigidbody component
//var r2d = GetComponent("Rigidbody2D");
float speed = 10.0f;
// Move the spaceship when an arrow key is pressed
if (Input.GetKey (KeyCode.RightArrow))
transform.position += Vector3.right * speed * Time.deltaTime;
else if (Input.GetKey (KeyCode.LeftArrow))
transform.position += Vector3.left * speed * Time.deltaTime;
//BULLET
//When spacebar is pressed
if (Input.GetKeyDown(KeyCode.Space)) {
Instantiate(bullet, transform.position, Quaternion.identity);
}
}
}
bulletScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletScript : MonoBehaviour {
public int speed = 8;
// Use this for initialization
void Start () {
Input.GetKey (KeyCode.UpArrow);
transform.position += Vector3.right * speed * Time.deltaTime;
}
void OnBecomeInvisible() {
Destroy (gameObject);
}
// Update is called once per frame
void Update () {
}
}
答案 0 :(得分:1)
正如他们在评论中告诉你的那样,你正在混合两种不同的方法。如果要使用Time.deltaTime
修改项目符号的位置,则需要将该行移至Update()
但是如果你想按照教程的方法,但不是从下到上射击子弹,你想从左到右射击,你应该只改变轴(并且不要忘记添加一个刚体到了子弹)
// Public variable
public var speed : int = 6;
// Function called once when the bullet is created
function Start () {
// Get the rigidbody component
var r2d = GetComponent("Rigidbody2D");
// Make the bullet move upward
r2d.velocity.x = speed;
}
// Function called when the object goes out of the screen
function OnBecameInvisible() {
// Destroy the bullet
Destroy(gameObject);
}