2d平台游戏中的敌人移动
本文关键字:敌人 移动 平台 游戏 2d | 更新日期: 2023-09-27 18:03:18
我花了至少两个小时研究如何让敌人角色在平台上左右移动而不掉下来。我已经尝试了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'
这里有一个非常简单的解决方案,可以帮助你开始。
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;
}
}