【问题标题】:Move an object from one side of the screen to the opposite Unity C#将对象从屏幕的一侧移动到对面的 Unity C#
【发布时间】:2020-12-15 17:13:32
【问题描述】:

我有一个 Sprite Player,它通过以下代码移动

using UnityEngine;

public class MovePlayer : MonoBehaviour
{
public Transform player;
[SerializeField]
private float speed = 10f;

void OnMouseDrag()
{
    if (!Player.lose) { 
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos.x = mousePos.x > 4.0f ? 4.0f : mousePos.x;
        mousePos.x = mousePos.x < -0.38f ? -0.38f : mousePos.x;
        player.position = Vector2.MoveTowards(player.position, 
            new Vector2(mousePos.x, player.position.y),
            speed * Time.deltaTime);
}
}
}

这两行用于锁定玩家向两侧的移动。

mousePos.x = mousePos.x > 4.0f ? 4.0f : mousePos.x;
mousePos.x = mousePos.x < -0.38f ? -0.38f : mousePos.x;

如果 Players Sprite 进入左侧屏幕边框,我该怎么做,它从右侧出现,相反

【问题讨论】:

    标签: c# unity3d 2d sprite


    【解决方案1】:

    检查这是否有帮助:

    private bool mouseInScreenX { get =>
        Input.mousePosition.x < Screen.width &&
        Input.mousePosition.x > 0; 
    }
    
    private bool mouseInScreenY { get =>
        Input.mousePosition.y < Screen.height &&
        Input.mousePosition.y > 0; 
    }
    
    private void Update() {
        if (!mouseInScreenX) 
            Input.mousePosition.x = 0;
            
        if (!mouseInScreenY)
            Input.mousePosition.y = 0;
    }
    

    没有调试过的代码,但我认为它足够准确,可以给你这个想法。 您可以使用 Screen 静态类而不是硬编码值来检查您是否在屏幕内。 如果需要保持拖拽,可以给被拖拽的实体鼠标位置。

    【讨论】:

      【解决方案2】:

      我刚刚添加了这段代码:

      if (player.position.x < -1)
                  player.position = new Vector3(player.position.x + 10f, player.position.y, player.position.z);
              else if (player.position.x > 5)
                  player.position = new Vector3(player.position.x - 10f, player.position.y, player.position.z);
      

      而不是这 2 行,它可以工作:

      mousePos.x = mousePos.x > 4.0f ? 4.0f : mousePos.x;
      mousePos.x = mousePos.x < -0.38f ? -0.38f : mousePos.x;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-13
        • 2017-07-21
        • 2023-03-31
        相关资源
        最近更新 更多