zl程序教程

您现在的位置是:首页 >  其他

当前栏目

游戏制作之路(17)模拟子弹的杀伤力

游戏模拟 制作 17
2023-09-14 09:10:43 时间

前面已经介绍了子弹发射出来,但目前子弹碰到物体并没有损伤,也就是说没有杀伤力。那么怎么样才可以让子弹碰到的物体有伤害,并且慢慢还要损坏。现在就来考虑这个问题,前面子弹是碰撞到物体就已经消失,但是有消息自动发给子弹的脚本,那么就是说子弹是可以知道碰到那一个物体的。如果拿到子弹碰撞到的物体,我们计算它的损坏情况,也就是怪物的生命值,当生命值减少到0就可以把这个物体删除掉,就可以了。因此,我们来创建一个脚本,让这个脚本来计算每个物体的生命值,如果生命值小于0,就把这个物体删除掉。如下添加一个脚本,脚本的名称叫做:EnemyHealth,

接着把这个脚本改名称,如下:

到这里,就把脚本创建好了,然后在脚本里添加下面的内容:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth : MonoBehaviour {

    public float initialHealth = 10.0f;

    private float currentHealth;
    // Use this for initialization
    void Start () {
        currentHealth = initialHealth;
    }
	
	// Update is called once per frame
	void Update () {
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;

        if (currentHealth < 0)
        {
            Destroy(gameObject);
        }
    }
}

这段脚本,就是创建initialHealth为生命的初始值,currentHealth为当前生命剩余值,如果小于0,就可以删除对象。

接着下来,我们把这个脚本拖到一个立方体,如下图:

这样就完成了一个怪物的伤害设置,其它怪物依次设置,但是要小心地板,不要设置这个,否则地板都会没有了,角色就腾空了。同样不能破坏的物体,都不要关联这个脚本。

最后在子弹里添加破坏物品的调用,如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rocket : MonoBehaviour {

    public float speed = 20.0f;
    public float life = 5.0f;

    public float damageDealt = 4.0f;
    // Use this for initialization
    void Start () {
        Invoke("Kill", life);
    }
	
	// Update is called once per frame
	void Update () {
        transform.position += transform.forward * speed * Time.deltaTime;

    }

    void OnTriggerEnter(Collider col)
    {
        EnemyHealth health = col.gameObject.GetComponent<EnemyHealth>();

        if (health != null)
        {
            health.TakeDamage(damageDealt);
        }

        Kill();
    }

    void Kill()
    {
        Destroy(gameObject);
    }
}

在这里,通过col参数来获取子弹碰到的物体,或者说怪物。如果没有设置这个脚本,就获取EnemyHealth脚本对象为null,所以这里要添加if判断,比如地板就没有这个脚本,就不能损坏它。

好吧,到这里,你就可以使用子弹来杀怪物了。

TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901