Unity 2D 效應器與來回移動的實現


1.效應器

Point Effector 2D: 點效應器。進入區域,吸引或排斥物體

 

Area Effector 2D: 區域效應器,可以用來做馬里奧的管道移動效果

 

Surface Effector 2D :表面效應器。實現傳送帶效果

 

PlatForm Effector 2D:平台效應器。實現2D游戲里面的台階效果

2.控制移動

// Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.A))
        {
            MoveLeft();
        }
        if (Input.GetKey(KeyCode.D))
        {
            MoveRight();
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }
        void MoveLeft()
    {
        var v = rgbd.velocity;
        v.x = -movespeed;
        rgbd.velocity = v;
        //gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.left * movespeed, ForceMode2D.Force);
    }

    void MoveRight()
    {
        var v = rgbd.velocity;
        v.x = movespeed;
        rgbd.velocity = v;
        //gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.right * movespeed, ForceMode2D.Force);
    }

    public void Jump()
    {
        if (isground)
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpspeed, ForceMode2D.Impulse);
            isground = false;
        }
        
    }

3.敵人來回移動

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

public class laihui : MonoBehaviour {

    public float movespeed=3.0f;
    private Vector2 currentposition;
    public float distnation=10.0f;
    private int face = 1;

    // Use this for initialization
    void Start () {
        currentposition = gameObject.transform.position;
    }
    
    // Update is called once per frame
    void Update () {
        if (face == 1)
        {
            gameObject.transform.Translate(Vector2.right * movespeed * Time.deltaTime);
        }
        if (face == 0)
        {
            gameObject.transform.Translate(Vector2.left * movespeed * Time.deltaTime);
        }
        if (gameObject.transform.position.x > currentposition.x+distnation)
        {
            face = 0;
        }
        if (gameObject.transform.position.x < currentposition.x)
        {
            face = 1;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM