【发布时间】:2019-03-09 00:59:18
【问题描述】:
我刚刚开始使用 Unity,我正在使用面向角色的 OOP 原则制作一个基本的 2d 游戏。 我创建了一个名为 EnemyController 的通用敌人类,它有一个名为 BasicEnemy 的子类。
这个想法是,当敌人产生时(在两个点之间,在这种情况下是床和酒吧),它要么向左要么向右移动并开始在物体之间巡逻。 我为此使用了光线投射,到目前为止,当敌人击中其中任何一个点时,我已经让光线与精灵一起翻转。 我似乎无法让精灵朝新翻转的方向移动。
我尝试修改父类中的moveSpeed变量,并尝试编写自己的移动函数LeftMove和RightMove强>。
我的代码如下。
这是父类的代码:
public class EnemyController : MonoBehaviour
{
//transform for each of the enemies
protected Transform enemyTransform;
protected Vector2 startPosition;
protected int damageValue, healthLevel;
public int moveSpeed;
protected int randNum;
protected Rigidbody2D rb;
private void Start()
{
enemyTransform = transform;
startPosition = enemyTransform.position;
rb = GetComponent<Rigidbody2D>();
randNum = Random.Range(1,3);
// Debug.Log(randNum);
if(randNum == 1) {
Debug.Log("Moves Left at the start");
} if(randNum == 2) {
Debug.Log("Moves Right at the start");
Flip();
}
}
private void FixedUpdate()
{
Move();
}
protected virtual void Move()
{
if(randNum == 1) {
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
}
if(randNum == 2) {
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}
}
public void Flip() {
Vector3 enemyScale = transform.localScale;
enemyScale.x *= -1;
transform.localScale = enemyScale;
}
}
这是 Child 类的代码:
public class BasicEnemy : EnemyController
{
//Origin, Direction, Range for Raycasting.
public Transform rayOriginPoint;
private Vector2 rayDir = new Vector2(-1,0);
public float range;
//GameObjects that it should hit
GameObject bar, bed;
EnemyController parentClass;
private void Start()
{
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
}
private void Update()
{
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true) {
if(hitObject.collider.name == bed.name) {
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
LeftMove();
}
if(hitObject.collider.name == bar.name) {
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
RightMove();
}
}
}
void LeftMove() {
rb.velocity = new Vector2(-1, rb.velocity.y);
}
void RightMove(){
rb.velocity = new Vector2(1, rb.velocity.y);
}
}
有人可以帮我解决这个问题吗? 提前致谢!
【问题讨论】:
-
为什么不只是翻转精灵而不是改变比例?然后使用 x/y 作为它们的自然轴
-
@BugFinder 不会和我写的 Flip 函数一样吗?照原样,精灵翻转。你能给我一个代码示例来理解吗? :)
-
GetComponent
().flipX = true; transform.scale 改变了其他东西。 -
@BugFinder 还有一些对撞机和其他东西也需要翻转。这就是我使用 transform.scale 位的原因。主要是因为我对此有点陌生。
-
如果你的敌人向 + 或 - 移动方向移动,看起来 randNum 会发生变化,而这在你的 Flip 函数中永远不会改变