U3D 飞机大战(MVC模式)解析--面向对象编程思想

  在自己研究U3D游戏的时候,看过一些人的简单的游戏开发视频,写的不错,只是个人是java web 开发的人,所以结合着MVC思想,对游戏开发进行了一番考虑。

如果能把游戏更加的思想化,分工化,开发便明了很多。

  这是游戏开发的元素。基于面向对象开发,首先将这些游戏对象面向对象化

主角对象(GameObject):

    主角移动方法(function)--通过接收键盘事件,对主角进行移动。

    子弹发射方法(function)--实例化子弹,赋予子弹初始位置,调用子弹本身的移动方法。

敌人对象(GameObject):

  敌人移动方法(function)--敌人初始化能够移动方法

  敌人发射子弹方法(function)--隔一段事件实例化子弹,赋予子弹初始化位置,调用子弹本身的移动方法。

子弹对象(GameObject):

  威力属性(property)--用来判断对被击中物体造成额度伤害。

 子弹移动方法(function)--子弹具有移动方法。

一般开发,主角对象(Sprite) 里面绑定一个脚本有一个Update,基本写在Update函数里面,移动,子弹发射就能够完成,

这样,虽然能够完成想要的效果,可是,这样面向对象的思想不强,就如同,一条流水线组装一样,你一个人其实也都能够搞定,可是如果分开来,一个人一个步骤,那样就更加简单了。

模拟一个普通脚本:

public class Player : MonoBehaviour{

    void Update(){
        if(按下xx键){
        move();
        }
    }
    //移动函数
    void move(){

    }
}

 也能够实现通过控制键盘,使操作游戏对象进行移动

加入MVC的思想,思路就清晰些,模型,也就是对象,就只具有对象的属性和方法,不具备实质性的行为,单纯的就是个模型罢了

视图就是游戏对象(GameObject)

模型就是该对象的属性,方法的C##文件

控制器就是对加入的一些逻辑和调用模型的类

那么模拟下代码

模型:

public class PlayerModel : MonoBehaviour{

    void Update(){

    }
    //移动函数
    void move(){

    }
}

控制器:

public class PlayerAction : MonoBehaviour{

    void Start(){
        PlayerModel play = gameobject.GetCompent<PlayerModel>();
     }
    void Update(){
        if(按下xx键){
        play.move();
        }
    }

}

这样,就能够把逻辑和调用都写到控制器里面,不扰乱模型,模型就只有方法和属性,不具备具体的行为

来一个例子:

代码:PlayerAction

using UnityEngine;
using System.Collections;
/*
 * Adminer:sun2955
 * http:www.yinghy.com
 * */
public class PlayerAction : MonoBehaviour {

    // 使用进行初始化
    void Start () {
    
    }
    
    //每一帧都会调用该函数
    void Update () {
        PlayerModel player = gameObject.GetComponent<PlayerModel>();
        player.Move();
    }
    //物理运动
    void FixedUpdate() 
    {

    }
}

PlayerAction:

using UnityEngine;
using System.Collections;
/*
 * Adminer:sun2955
 * http:www.yinghy.com
 * */
public class PlayerModel : MonoBehaviour {
    public GameObject xxx;//子弹对象
    private Vector2 speed = new Vector2(25, 25);
    private Vector2 movement;
    // 使用进行初始化
    void Start () {
    
    }
    
    //每一帧都会调用该函数
    void Update () {
    
    }
    //物理运动
    void FixedUpdate() 
    {

    }
    public void Move() {
        float inputx = Input.GetAxis("Horizontal"); //获得水平移动
        float inputy = Input.GetAxis("Vertical"); //获得垂直移动
        Debug.LogError("inputx=" + inputx + "inputy=" + inputy);
        movement = new Vector2(inputx * speed.x, inputy * speed.y);
        if (Input.GetKey(KeyCode.K))
        {
            //发射子弹 实例化该子弹,得到子弹的对象,然后调用子弹的移动方法;
            GameObject xxgame = GameObject.Instantiate(xxx);
            xxgame.gameObject.transform.position = gameObject.transform.position;
            xxgame.gameObject.GetComponent<shootscript>().move();
            xxgame.gameObject.GetComponent<shootscript>().shootsound();

        }
        //这样可以达到物理性质的运动
        gameObject.GetComponent<Rigidbody2D>().velocity = movement;
    } 
}

出来的效果:

原文地址:https://www.cnblogs.com/sunxun/p/5066822.html