学习坦克大战

2019-2-1

学习到坦克大战的第14课
由于有些代码不会写,耽误了挺长时间
写了防止坦克移动时斜着走的代码,
写了坦克发射子弹的代码,
学习了防止坦克碰墙鬼畜的方法:在FixedUpdate函数中写移动代码
学习了如何通过欧拉角转四元数的方法:Quaternion.Euler(Rot)
可以调整子弹发射方向


学习坦克大战_第1张图片
坦克

player代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.PlayerLoop;

public class Player : MonoBehaviour
{
    //定义一个左右开关,一个上下开关
    public float Speed = 1;
    public Sprite[] TankSprites;
    public GameObject Bullet;
    private Vector2 Dre;
    private Vector3 Rot;

    private bool _canHorizontal;
    private bool _canVertical;
    private SpriteRenderer sr;

    //枚举类型
    
    private void Awake()
    {
        sr = GetComponent();
    }

    // Start is called before the first frame update
    void Start()
    {
        _canHorizontal = false;
        _canVertical = false;
    }

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

    void FixedUpdate()
    {
        Move();
        Attack();
    }

    void Attack()
    { //坦克攻击,按空格实例化一个子弹
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject b = GameObject.Instantiate(Bullet, transform.position,Quaternion.Euler(Rot));
            Rigidbody2D rgd = b.GetComponent();

            rgd.velocity = Dre * Speed * 3;
        }
    }

    void Move()//移动时修改子弹以及坦克的方向
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        if (h != 0)
        {
            isHorizontal();
        }
        if (v != 0)
        {
            isVertical();
        }
        if (_canHorizontal)//如果可以水平移动
        {
            transform.Translate(Vector3.right * h * Time.deltaTime * Speed);
            if (h < 0)
            {
                Dre = new Vector2(-1, 0);
                Rot = new Vector3(0, 0, 90);
                sr.sprite = TankSprites[3];
            }
            else if (h > 0)
            {
                Dre = new Vector2(1, 0);
                Rot = new Vector3(0, 0, -90);
                sr.sprite = TankSprites[1];
            }
        }
        if (_canVertical)//如果可以垂直移动
        {
            transform.Translate(Vector3.up * v * Time.deltaTime * Speed);
            if (v < 0)
            {
                Dre = new Vector2(0, -1);
                Rot = new Vector3(0, 0, 180);
                sr.sprite = TankSprites[2];
            }
            else if (v > 0)
            {
                Dre = new Vector2(0, 1);
                Rot = new Vector3(0, 0, 0);
                sr.sprite = TankSprites[0];
            }
        }

    }
    //判断水平移动
    void isHorizontal()
    {
        _canHorizontal = true;
        _canVertical = false;
    }
    //判断是否在垂直移动
    void isVertical()
    {
        _canHorizontal = false;
        _canVertical = true;
    }

}

这几天由于LOL出了无限火力耽搁了,安逸和勤劳只能选择劳逸结合。

你可能感兴趣的:(学习坦克大战)