【发布时间】:2018-02-11 21:09:19
【问题描述】:
我有一个测试 2D 游戏,我的玩家从左到右移动,当他到达屏幕的尽头时,它只会在另一侧变换。我改变了主意,让我的球员斜着走。它确实有效,但我不知道如何让播放器在到达屏幕末端时停止。我不希望它在另一边发生变化,而只是停下来。到目前为止,我所有的结果要么是边缘出现了一些故障,要么根本没有停止。我提供了我的 PlayerController 脚本。现在我的球员沿对角线移动,他将在屏幕边缘后继续前进。如果有人可以帮助我,我将不胜感激。我从没想过我会处理对角线运动,但我真的很想学习如何去做。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
public float speed = 7;
public float speedy = 7;
public event System.Action OnPlayerDeath;
float screenHalfWidthInWorldUnits;
Rigidbody2D rb;
void Start () {
rb = GetComponent<Rigidbody2D>();
float halfPlayerWidth = transform.localScale.x / 2f;
screenHalfWidthInWorldUnits = Camera.main.aspect * Camera.main.orthographicSize;
}
void Update()
{
float inputX = Input.GetAxisRaw("Horizontal");
float velocity = inputX * speed;
transform.Translate(Vector2.right * velocity * Time.deltaTime);
}
public void MoveRight()
{
rb.velocity = new Vector2(speed, speedy);
}
public void MoveLeft()
{
rb.velocity = new Vector2(-speed, -speedy);
}
public void Stop()
{
rb.velocity = Vector2.zero;
}
void OnTriggerEnter2D(Collider2D triggerCollider)
{
if (triggerCollider.tag =="Box")
{
if (OnPlayerDeath != null)
{
OnPlayerDeath();
}
Destroy(gameObject);
}
}
}
【问题讨论】:
-
你想在到达边缘时摧毁玩家吗?
-
为什么不在你想限制玩家的地方创建碰撞器?
-
@MGDroid 不,我只是想让他停下来。当它向左或向右时它工作得很好,但是对角线,我错过了一些东西。
-
快速提问,为什么要使用
transform.Translate移动播放器,而不是使用MoveRight()和MoveLeft()方法? (目前这将忽略物理对象,例如对撞机。) -
是否可以添加有关情况和问题的短视频/gif?我有点难以想象发生了什么。
标签: unity3d unity5 unity3d-2dtools