2D游戏场景

2017-03-12  本文已影响282人  大批

创建2D游戏工程,和场景


创建工作层


添加静态的物体


添加角色和控制

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwanMove : MonoBehaviour {

    private float moveSpeed = 4;//移动的速度

    // Use this for initialization
    void Start () {
        //设置初始位置
        transform.position = new Vector3(22,3,0);
    }
    
    // Update is called once per frame
    void Update () {
        if (transform.position.x > -22)
        {
            //移动
            transform.Translate(Vector3.right * -moveSpeed * Time.deltaTime);
        }
        else {
            transform.position = new Vector3(22, 3, 0);
        }
    }
}

创建主要的游戏对象

public class GameController : MonoBehaviour {

    public GameObject ball;//保龄球
    private float maxWidth;
    private float time = 2;
    private GameObject newball;

    // Use this for initialization
    void Start () {
        //将屏幕的宽度转换成世界坐标
        Vector3 screenPos = new Vector3(Screen.width, 0, 0);
        Vector3 moveWidth = Camera.main.ScreenToWorldPoint(screenPos);

        //获取保龄球自身的宽度
        float ballWidth = ball.GetComponent<Renderer>().bounds.extents.x;

        //计算保龄球实例化位置的宽度
        maxWidth = moveWidth.x - ballWidth;
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    private void FixedUpdate()
    {
        time -= Time.deltaTime;
        if (time < 0) {
            time = Random.Range(1.5f, 2.0f);
            float posX = Random.Range(-maxWidth, maxWidth);
            Vector3 spawnPosition = new Vector3(posX,transform.position.y,0);
            newball = Instantiate(ball, spawnPosition, Quaternion.identity);
            Destroy(newball, 10);
        }
    }
}
public class HatController : MonoBehaviour {

    private Vector3 rawPosition;
    private Vector3 hatPosition;
    private float maxWidth;
    // Use this for initialization
    void Start () {
        Vector3 screenPos = new Vector3(Screen.width,0,0);
        Vector3 moveWidth = Camera.main.ScreenToWorldPoint(screenPos);

        float hatW = GetComponent<Renderer>().bounds.extents.x;
        hatPosition = transform.position;
        maxWidth = moveWidth.x - hatW;

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

    private void FixedUpdate()
    {
        rawPosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
        hatPosition = new Vector3(rawPosition.x, hatPosition.y, 0);
        hatPosition.x = Mathf.Clamp(hatPosition.x, -maxWidth, maxWidth);
        GetComponent<Rigidbody2D>().MovePosition(hatPosition);
    }
}

创建2D阻挡物


添加2D效果


Nothing is certain in this life. The only thing i know for sure is that. I love you and my life. That is the only thing i know. have a good day

:)

上一篇 下一篇

猜你喜欢

热点阅读