游戏制作之路(21)代码整理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caimouse/article/details/82585907

前面介绍了角色是否到达地面的检测,并且代码都是不断地添加进来的,并没有进行整体的设计,你会发现代码的效率有点低了。在这里,我们来把代码整理一下,让这些代码更加高效,并且更加有条理,更容易理解。在代码里,发现如下的代码:
GetComponent<CharacterController>()
已经引用两遍了,这样会导致需要查找这个角色组件两遍,这样效率就会降低,所以在类里就可以定义一个CharacterController对象,用来保存角色对象,这样就不用每帧更新游戏时,再查找两遍。因此,在类里添加一行代码如下:
private CharacterController controller;
并且controller只需要在Start()函数里更新一次,就保存了角色对象,不用每次更新帧时才获取,这样大地提高了脚本的效率。
接着下来,我们来定义一个移动的速度moveVelocity,让这个移动速度只能在地面进行移动,不能在空中移动,因为这个角色不是飞机,不能凭空飞行。添加一行定义变量:
private Vector3 moveVelocity = Vector3.zero;

接着下来,就会把代码修改成这样:

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

public class BasicMovement : MonoBehaviour {

    public float speed = 10.0f;
    public float rotationSpeed = 2.0f;
    public Transform head;
    public float maxHeadRotation = 80.0f;
    public float minHeadRotation = -80.0f;
    private float currentHeadRotation = 0;

    private float yVelocity = 0;
    public float jumpSpeed = 15.0f;
    public float gravity = 30.0f;

    private CharacterController controller;
    private Vector3 moveVelocity = Vector3.zero;

    // Use this for initialization
    void Start () {
        controller = GetComponent<CharacterController>();
    }
	
	// Update is called once per frame
	void Update () {
        Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

        if (controller.isGrounded)
        {
            yVelocity = 0;

            if (Input.GetButtonDown("Jump"))
            {
                yVelocity = jumpSpeed;
            }

            moveVelocity = transform.TransformDirection(new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"))) * speed;
        }

        yVelocity -= gravity * Time.deltaTime;

        transform.Rotate(Vector3.up, mouseInput.x * rotationSpeed);

        currentHeadRotation = Mathf.Clamp(currentHeadRotation + mouseInput.y * rotationSpeed, minHeadRotation, maxHeadRotation);

        head.localRotation = Quaternion.identity;
        head.Rotate(Vector3.left, currentHeadRotation);

        Vector3 velocity = moveVelocity + yVelocity * Vector3.up;

        controller.Move(velocity * Time.deltaTime);
    }
}

在这里,已经判断接触地面,才开始进行移动,所以放在接地判断的条件语句里面。下面这行:

Vector3 velocity = moveVelocity + yVelocity * Vector3.up;

就是把平面的移动速度和向上跳动、落下的速度进行组合。然后一起在controller.Move里移动,这样就构成一个完美的角色控制系统。

到这里,已经实现游戏基本的功能,你可以尽情地玩了。

跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/82585907