gpt4 book ai didi

c# - 使用 UI 按钮移动游戏对象

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:00 25 4
gpt4 key购买 nike

我正在尝试通过 UI 按钮设置对 Player 游戏对象的控制。2d 自上而下 View 场景。

当我释放左/右/上/下 ui 按钮时,我想在固定距离(Axix X 左右方向为 0.8,上下方向为 2.4)上平滑地传输 Player 对象。

我在这里找到了平滑移动的代码,但是当按下 ui 按钮时,Player 一直在移动。

你能帮我让它在鼠标向上(指针向上)时移动并移动 public x= 0.8f 左/右,public y = 2.4f 向上/向下

同时我想对 x 轴和 y 轴上的移动使用不同的速度(peblic)

如果它应该完全是使用 smth 的其他脚本,比如 transform.translate,那也没关系请指导任何可能的解决方案。谢谢

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerControl : MonoBehaviour
{

float movX;
float movY;
Rigidbody2D rb;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}

void Update()
{
movX = CrossPlatformInputManager.GetAxisRaw("Horizontal");
movY = CrossPlatformInputManager.GetAxisRaw("Vertical");

rb.velocity = new Vector2(movX * 1, movY * 1);

}
}

最佳答案

此脚本可以通过 WASD 键移动。这应该在 x 时间量(速度)内按请求的量移动您的游戏对象。目前它只能在到达目的地时移动,但您可以通过停止协程轻松修改它:)

using System.Collections;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
// We gonna move by WASD keys

[Header("Speed & Movement settings")]
[SerializeField]
float Speed = 2.0f;
[SerializeField]
float movSpeedX = 0.8f;
[SerializeField]
float movSpeedY = 2.4f;

bool ReachedTarget = true;

void Update()
{
if (ReachedTarget)
{
Vector2 dest = Vector2.zero;
Vector2 currentPos = transform.position;
if (Input.GetKeyUp(KeyCode.W))
{
dest = currentPos + (Vector2.up * movSpeedY);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.S))
{
dest = currentPos + (Vector2.down * movSpeedY);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.D))
{
dest = currentPos + (Vector2.right * movSpeedX);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.A))
{
dest = currentPos + (Vector2.left * movSpeedX);
StartCoroutine(moveTo(dest, Speed));
}
}
}

// Time to take is in seconds
IEnumerator moveTo(Vector2 TargetPosition, float TimetoTake)
{
Vector2 originalPosition = transform.position;
float Time_taken = 0f;
ReachedTarget = false;
while (Time_taken < 1)
{
Time_taken += Time.deltaTime / TimetoTake;
// Interpolating between the original and target position this basically provides your "speed"
transform.position = Vector2.Lerp(originalPosition, TargetPosition, Time_taken);
yield return null;
}
Time_taken = 0;
transform.position = TargetPosition;
ReachedTarget = true;
}
}

关于c# - 使用 UI 按钮移动游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com