下面是发射子弹的代码
(以一个飞船发射子弹为例子)
飞机的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playercontroller : MonoBehaviour {
public float movespeed = 5f; //飞行速度
public Transform shell; //子弹
Vector3 movement; //方向矢量
Rigidbody playerrigidbody; //定义飞机的rigidbody
GameObject enemy; //敌人
void Awake()
{
enemy = GameObject.FindGameObjectWithTag("enemy");
//通过tag 找到敌人
}
void Start () {
playerrigidbody = GetComponent<Rigidbody>();//获取飞机的rigidbody
}
void Update()
{
if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0))
{
Instantiate(shell,transform.position, shell.transform.rotation); //发射子弹的代码(实例化一个子弹)
}
}
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
move(h, v);
}
//飞机飞行的代码
void move(float h,float v)
{
movement.Set(h, 0f, v);
movement = movement.normalized * movespeed * Time.deltaTime;
transform.position = movement + transform.position;
playerrigidbody.MovePosition(transform.position);
}
//飞机的碰撞器上有一个触发器
//飞机撞到别的物体就爆炸
void OnTriggerEnter(Collider other)
{
if (other.gameObject == enemy)
{
score.Score += 10;
Destroy(enemy.gameObject,0f);
Destroy(this.gameObject, 0f);
}
}
}
子弹的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shell : MonoBehaviour {
public float shell_speed = 10f; //子弹飞行速度
protected Transform m_transform;
GameObject enemy; //敌人
int scorevalue = 5;
void Awake()
{
enemy = GameObject.FindGameObjectWithTag("enemy");
}
void Start()
{
m_transform = this.transform;
Destroy(this.gameObject, 1f); //发射后1秒Destory子弹
}
void Update()
{
m_transform.Translate(new Vector3(0, 0, shell_speed * Time.deltaTime)); //子弹沿着z轴方向飞行
}
//子弹撞到敌人后敌人消失
void OnTriggerEnter(Collider other)
{
if (other.gameObject == enemy)
{
score.Score = score.Score+scorevalue;
Destroy(enemy.gameObject,0f);
}
}
}
新人练手,不妥之处望大神们指教
个人觉得这个代码有点麻烦,希望有大神能讲一个简单的代码