3D游戏编程——空间与运动

一.简答题

游戏对象运动的本质是什么?

游戏对象运动的本质就是使用矩阵变换(平移,旋转,缩放)改变游戏对象的空间属性。

请用三种方法以上方法,实现物体的抛物线运动。(如,修改Transform属性,使用向量Vector3的方法…)

1.直接改position

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

public class Move : MonoBehaviour {

    private float speedx;
    private float speedy;
	// Use this for initialization
	void Start () {
		speedx = 5;
		speedy = 5;
	}
	// Update is called once per frame
	void Update () {
	    speedy = speedy - Time.deltaTime;
        this.transform.position += speedx * Vector3.left * Time.deltaTime;
        this.transform.position += speedy * Vector3.down * Time.deltaTime;
    }
}

2.使用平移方法Translate

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

public class move : MonoBehaviour
{

    private float speedx;
    private float speedy;
	// Use this for initialization
	void Start () {
		speedx = 5;
		speedy = 5;
	}

    void Update()
    {
        speedy = speedy - Time.deltaTime;
        Vector3 var = new Vector3(speedx, speedy, 0) * Time.deltaTime;
        this.transform.Translate(var);
    }
}

3.利用MoveTowards方法

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

public class move : MonoBehaviour
{

    private float speedx;
    private float speedy;
	// Use this for initialization
	void Start () {
		speedx = 5;
		speedy = 5;
	}

    void Update()
    {
        speedy = speedy - Time.deltaTime;
        Vector3 var = new Vector3(speedx, speedy, 0) * Time.deltaTime + this.transform.position;
        this.transform.position = Vector3.MoveTowards(this.transform.position, var, 10);
    }
}

写一个程序,实现一个完整的太阳系, 其他星球围绕太阳的转速必须不一样,且不在一个法平面上。

首先创建如下结构 sun 里包括8大行星, 并且设置好距离和大小:
在这里插入图片描述
然后编写如下c#脚本:

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

public class plantMove : MonoBehaviour
{

    // Use this for initialization  
    void Start()
    {
   
    }

    // Update is called once per frame  
    void Update()
    {

        GameObject.Find("Sun").transform.Rotate(Vector3.up * Time.deltaTime * 5 );

        GameObject.Find("Mercury").transform.RotateAround(Vector3.zero, new Vector3(0.1f, 1, 0), 60 * Time.deltaTime);
        //设置公转的方向和速度  方向轴为(0, 1, 0) 速度为 60
        GameObject.Find("Mercury").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 58);
        //设置自转 自转速度为10000/58   58是水星的自传周期  倒数就是时间  下同

        GameObject.Find("Venus").transform.RotateAround(Vector3.zero, new Vector3(0, 1, -0.1f), 55 * Time.deltaTime);
        GameObject.Find("Venus").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 243);

        GameObject.Find("Earth").transform.RotateAround(Vector3.zero, new Vector3(0, 1, 0), 50 * Time.deltaTime);
        GameObject.Find("Earth").transform.Rotate(Vector3.up * Time.deltaTime * 10000);

        GameObject.Find("Mars").transform.RotateAround(Vector3.zero, new Vector3(0.2f, 1, 0), 45 * Time.deltaTime);
        GameObject.Find("Mars").transform.Rotate(Vector3.up * Time.deltaTime * 10000);

        GameObject.Find("Jupiter").transform.RotateAround(Vector3.zero, new Vector3(-0.1f, 2, 0), 35 * Time.deltaTime);
        GameObject.Find("Jupiter").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 0.3f);

        GameObject.Find("Saturn").transform.RotateAround(Vector3.zero, new Vector3(0, 1, 0.2f), 20 * Time.deltaTime);
        GameObject.Find("Saturn").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 0.4f);

        GameObject.Find("Uranus").transform.RotateAround(Vector3.zero, new Vector3(0, 2, 0.1f), 15 * Time.deltaTime);
        GameObject.Find("Uranus").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 0.6f);

        GameObject.Find("Neptune").transform.RotateAround(Vector3.zero, new Vector3(-0.1f, 1, -0.1f), 10 * Time.deltaTime);
        GameObject.Find("Neptune").transform.Rotate(Vector3.up * Time.deltaTime * 10000 / 0.7f);

    }
}

通过GameObject.Find来找到各个球体 然后通过调用RotateAround设置公转,通过调用Rotate方法设置自转。
可以看到各个星球的公转和自转:
在这里插入图片描述

二.编程实践

阅读以下游戏脚本:

Priests and Devils
Priests and Devils is a puzzle game in which you will help the Priests and Devils to cross the river within the time limit. There are 3 priests and 3 devils at one side of the river. They all want to get to the other side of this river, but there is only one boat and this boat can only carry two persons each time. And there must be one person steering the boat from one side to the other side. In the flash game, you can click on them to move them and click the go button to move the boat to the other direction. If the priests are out numbered by the devils on either side of the river, they get killed and the game is over. You can try it in many > ways. Keep all priests alive! Good luck!

程序需要满足的要求:

  • play the game ( http://www.flash-game.net/game/2535/priests-and-devils.html )
  • 列出游戏中提及的事物(Objects)
  • 用表格列出玩家动作表(规则表),注意,动作越少越好
  • 请将游戏中对象做成预制
  • 在 GenGameObjects 中创建 长方形、正方形、球 及其色彩代表游戏中的对象。
  • 使用 C# 集合类型 有效组织对象
  • 整个游戏仅 主摄像机 和 一个 Empty 对象, 其他对象必须代码动态生成!!! 。 整个游戏不许出现 Find 游戏对象, SendMessage 这类突破程序结构的 通讯耦合 语句。 违背本条准则,不给分
  • 请使用课件架构图编程,不接受非 MVC 结构程序
  • 注意细节,例如:船未靠岸,牧师与魔鬼上下船运动中,均不能接受用户事件!

列出游戏中提及的事物

在这个游戏中提及的事物有:3个牧师、3个恶魔、2个河岸、1个船和1条河。

用表格列出玩家动作表(规则表)

动作条件
船从起点到终点船在起点,船上至少一个人
船从终点到起点船在终点,船上至少一个人
牧师上船船上有至少一个空位
恶魔上船船上有至少一个空位
牧师下船船上有牧师
恶魔下船船上有恶魔

首先我们要做好预设:
在这里插入图片描述
之后我们开始写代码。
Director部分,我们实现成单例模式,再实现sceneController与UserAction两个接口:

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


namespace baseCode
{
    public class Director : System.Object
    {
        private static Director _instance;
        public sceneController currentSceneController { get; set; }

        public sceneController CurrentScenceController { get; set; }
        public static Director getInstance()
        {
            if (_instance == null)
            {

                _instance = new Director();
            }
            return _instance;
        }
    }

    public interface sceneController
    {
        void loadResources();

    }
}


public interface UserAction
{

}

public interface firstScenceUserAction : UserAction
{
    void boatMove();
    void getBoatOrGetShore(string name);
    void reset();
    string getStatus();
}

我的代码的大部分都是在GenGameObject里面的,这个文件负责创建游戏中的对象,并且完成了对象控制器的实现,我们先来看一下各个控制器的实现:

船的控制器:

public class boatController
{
    GameObject boat;
    readonly boatMoveBeahave updateBoatMove;
    readonly firstScenceSolveClick toSolveClick;
    Vector3 leftPos = new Vector3(-4f, 0.7f, 0f);
    Vector3 rightPos = new Vector3(4f, 0.7f, 0f);
    string[] nameOfPeopleOnBoat = { "", "" };
    Vector3[] boatPos = { new Vector3(-0.25f, 1.5f, 0f), new Vector3(0.25f, 1.5f, 0f) };
    public string size;
    private string defaultSize;

    public boatController(string size)
    {
        boat = Object.Instantiate(Resources.Load("Prefabs/Boat", typeof(GameObject))
            , rightPos, Quaternion.identity, null) as GameObject;
        boat.name = "boat";
        toSolveClick = boat.AddComponent(typeof(firstScenceSolveClick)) as firstScenceSolveClick;
        toSolveClick.setName(boat.name);
        updateBoatMove = boat.AddComponent(typeof(boatMoveBeahave)) as boatMoveBeahave;
        defaultSize = size;
        this.size = defaultSize;
    }

    public bool ifEmpty()
    {
        return nameOfPeopleOnBoat[0] == "" && nameOfPeopleOnBoat[1] == "";
    }
    public bool ifHaveSeat()
    {
        return nameOfPeopleOnBoat[0] == "" || nameOfPeopleOnBoat[1] == "";
    }

    public void move()
    {
        if (size == "right")
        {
            updateBoatMove.setAim(leftPos);
            size = "left";
        }
        else
        {
            updateBoatMove.setAim(rightPos);
            size = "right";
        }
    }

    public string getRunningState()
    {
        return updateBoatMove.getState();
    }

    public string[] getPassengerName()
    {
        return nameOfPeopleOnBoat;
    }

    public GameObject getBoat()
    {
        return boat;
    }

    public void outBoat(string name)
    {
        if (nameOfPeopleOnBoat[0] == name)
        {
            nameOfPeopleOnBoat[0] = "";
        }
        else if (nameOfPeopleOnBoat[1] == name)
        {
            nameOfPeopleOnBoat[1] = "";
        }
    }

    public Vector3 getBoatPos(string name)
    {
        Vector3 result = Vector3.zero;
        for (int loop = 0; loop < 2; loop++)
        {
            if (nameOfPeopleOnBoat[loop].Length == 0)
            {
                nameOfPeopleOnBoat[loop] = name;
                result = boatPos[loop];
                break;
            }
        }
        return result;
    }

    public void reset()
    {
        nameOfPeopleOnBoat[0] = nameOfPeopleOnBoat[1] = "";
        size = defaultSize;
        updateBoatMove.setAim(rightPos);
    }
}

其中实现了船的移动、上船和下船等方法以及生成了船对象。

人的控制器:

public class peopleController
{

    GameObject people;
    private string status;
    public string size;
    private string defaultSize;
    firstScenceSolveClick solveClick;
    int number;

    public peopleController(string name, int number, Vector3 pos, string status, string size)
    {
        people = Object.Instantiate(Resources.Load("Prefabs/" + name, typeof(GameObject))
            , pos, Quaternion.identity, null) as GameObject;
        people.name = name + number.ToString();
        solveClick = people.AddComponent(typeof(firstScenceSolveClick)) as firstScenceSolveClick;
        solveClick.setName(people.name);
        this.number = number;
        this.status = status;
        defaultSize = size;
        this.size = size;
    }



    public string getName()
    {
        return people.name;
    }

    public string getStatus()
    {
        return status;
    }


    public void getOnBoat(boatController boatCtrl)
    {
        status = "boat";
        people.transform.parent = boatCtrl.getBoat().transform;
        people.transform.localPosition = boatCtrl.getBoatPos(getName());

    }

    public void getOffBoat(environmentController envCtrl)
    {
        status = "shore";
        people.transform.parent = null;
        people.transform.position = envCtrl.getPosVec(size, number);
    }

    public void reset(environmentController envCtrl)
    {
        status = "shore";
        size = defaultSize;
        people.transform.parent = null;
        people.transform.position = envCtrl.getPosVec(size, number);
    }

}

其中实现了人的上船、下船以及生成人对象。

环境的控制器:

public class environmentController
{
    GameObject environment;
    Vector3 environmentPos = Vector3.zero;
    Vector3 leftShorePos = new Vector3(-6f, 2f, 0f);
    Vector3 rightShorePos = new Vector3(6f, 2f, 0f);
    public environmentController()
    {
        environment = Object.Instantiate(Resources.Load("Prefabs/environment", typeof(GameObject))
            , environmentPos, Quaternion.identity, null) as GameObject;
    }

    public Vector3 getPosVec(string size, int number)
    {

        Vector3 result = new Vector3(0, 0, 0);
        if (size == "right")
        {
            result = rightShorePos + number * Vector3.right;
        }
        else
        {
            result = leftShorePos + number * Vector3.left;
        }
        return result;
    }

}

主要是获取位置以及生成预设好的环境。

以及控制船运动的代码:

public class boatMoveBeahave : MonoBehaviour
{
    Vector3 aim = new Vector3(4f, 0.7f, 0f);
    float speed = 20.0f;
    string status = "waiting";

    void Update()
    {
        if (this.transform.position == aim)
        {
            status = "waiting";
        }
        else
        {
            this.transform.position = Vector3.MoveTowards(this.transform.position, aim, speed * Time.deltaTime);
        }
    }

    public void setAim(Vector3 aim)
    {
        this.aim = aim;
        status = "running";
    }

    public string getState()
    {
        return status;
    }
}

使用MoveTowards方法来实现运动。

接下来在firstScenceSolveClick文件中,我们实现了检测用户鼠标点击的事件,并通过接口,完成对事件的响应:

public class firstScenceSolveClick : MonoBehaviour
{
    firstScenceUserAction action;
    string characterName;
    // Use this for initialization
    void Start()
    {

        action = Director.getInstance().currentSceneController as firstScenceUserAction;

    }

    public void setName(string name)
    {
        characterName = name;
    }

    void Update()
    {
    }

    // Update is called once per frame
    void OnMouseDown()
    {
        if (action.getStatus() != "playing")
        {
            return;
        }
        else
        {
            if (characterName == "boat")
            {
                action.boatMove();
            }
            else
            {
                action.getBoatOrGetShore(name);
            }
        }


    }
}

最后在FirstSceneGuiCtrl文件中,我们实现了一些用户可以点击的按钮:

public class FirstSceneGuiCtrl : MonoBehaviour
{
    firstScenceUserAction action;
    bool ifShowHelp = true;
    string helpText = "黑色球为恶魔,白色方块为牧师,目标:让所有牧师和恶魔都到左岸,规则:点击牧师或者恶魔可以上岸或者上船,任意一边岸的恶魔" +
                      "数量若多于牧师(包括那一边船里的人物),那么游戏失败。";
    // Use this for initialization
    void Start()
    {
        action = Director.getInstance().currentSceneController as firstScenceUserAction;
    }

    // Update is called once per frame
    void OnGUI()
    {
        firstScenceUserAction action = Director.getInstance().currentSceneController as firstScenceUserAction;
        string status = action.getStatus();
        if (ifShowHelp == true)
        {
            GUI.Box(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 90, 200, 180), "");
            GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 90, 200, 180), helpText);
            if (GUI.Button(new Rect(Screen.width / 2 - 20, Screen.height / 2 + 60, 40, 30), "Ok"))
            {
                ifShowHelp = false;

            }

        }

        if (GUI.Button(new Rect(10, 10, 100, 50), "help"))
        {
            ifShowHelp = true;
        }



        if (status == "playing")
        {
            if (GUI.Button(new Rect(130, 10, 100, 50), "restart"))
            {
                action.reset();
            }
        }
        else
        {
            string showMsg;
            if (status == "lost")
            {
                showMsg = "you lose!!";
            }
            else
            {
                showMsg = "you win!!";
            }
            if (GUI.Button(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), showMsg))
            {
                action.reset();
            }
        }
    }
}

到这里我们差不多就做好了,我们来看一下效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值