【问题标题】:2d platformer enemy movement2d 平台游戏敌人移动
【发布时间】:2015-07-18 17:31:34
【问题描述】:

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

我的代码如下:

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'

【问题讨论】:

  • public var velocity: Vector2; 不是有效的字段声明,您需要像在两个紧接的声明中一样指定类型和名称。
  • 似乎您已将 Javascript 与 C# 代码混合在一起。 Vector2 速度变量定义看起来像 javascript。

标签: c# unity3d 2d


【解决方案1】:

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

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;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多