2d 平台游戏敌人运动

2d platformer enemy movement

我已经研究了至少两个小时如何制作一个在平台上左右移动而不会掉落的敌人角色。我已经尝试了 4 个不同的脚本并浏览了 2 个 youtube 教程,但我似乎在所有方面都遇到了错误。这是我的第一个 post 所以如果我做错了什么请通知我,谢谢 :)。

我的代码如下:

using UnityEngine;
using System.Collections;

public class EnemyPatrol : MonoBehaviour {

    public float MoveSpeed;
    public bool MoveRight;
    public var velocity: Vector2;

    void Update () 
    {
        if (MoveRight) {
            public bool GetComponent<rigidbody2D>().velocity = 
              new Vector2(MoveSpeed, rigidbody2D.velocity.y);
        } else {
            public bool GetComponent<rigidbody2D>().velocity = 
              new Vector2(-MoveSpeed, rigidbody2D.velocity.y);
        }
    }
}

我的错误:

Assets/Scripts/EnemyPatrol.cs(8,28): error CS1519: Unexpected symbol \`:' in class, struct, or interface member declaration  
Assets/Scripts/EnemyPatrol.cs(8,37): error CS1519: Unexpected symbol \`;' in class, struct, or interface member declaration  
Assets/Scripts/EnemyPatrol.cs(13,30): error CS1525: Unexpected symbol \`public'  
Assets/Scripts/EnemyPatrol.cs(15,30): error CS1525: Unexpected symbol \`public'

这是一个非常简单的解决方案,可以帮助您入门。

using UnityEngine;
using System.Collections;

public class EnemyPatrol : MonoBehaviour
{
    Rigidbody2D enemyRigidBody2D;
    public int UnitsToMove = 5;
    public float EnemySpeed = 500;
    public bool _isFacingRight;
    private float _startPos;
    private float _endPos;

    public bool _moveRight = true;


    // Use this for initialization
    public void Awake()
    {
         enemyRigidBody2D = GetComponent<Rigidbody2D>();
        _startPos = transform.position.x;
        _endPos = _startPos + UnitsToMove;
        _isFacingRight = transform.localScale.x > 0;
    }


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

    if (_moveRight)
    {
        enemyRigidBody2D.AddForce(Vector2.right * EnemySpeed * Time.deltaTime);
        if (!_isFacingRight)
            Flip();
    }

    if (enemyRigidBody2D.position.x >= _endPos)
        _moveRight = false;

    if (!_moveRight)
    {
        enemyRigidBody2D.AddForce(-Vector2.right * EnemySpeed * Time.deltaTime);
        if (_isFacingRight)
            Flip();
    }
    if (enemyRigidBody2D.position.x <= _startPos)
        _moveRight = true;


}

    public void Flip()
    {
        transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        _isFacingRight = transform.localScale.x > 0;
    }

}