【问题标题】:How can I reset the position of my player when touching a certain layer in unity?统一触摸某个图层时如何重置播放器的位置?
【发布时间】:2021-04-28 08:13:24
【问题描述】:

当我触摸“死亡”层时,我正在尝试重置我的玩家的位置(到 0、2、0)。我该怎么做?

我尝试使用名为isDeadbool,我的代码如下所示:

if(isDead)
{
   transform.position = new Vector3(0f, 2f,0f);
}

这是我的全部代码,可能会有所帮助

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovementScript : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;

    public float gravity = -9.81f;

scripts
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    public float jumpHeight = 3f;

    Vector3 velocity;
    bool isGrounded;
    bool isDead;
    // Update is called once per frame
    void Update()
    {

        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);


for evig når den treffer bakken
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

            float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);
        controller.Move(velocity * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;
    }
}

我不知道该怎么做。有什么建议?谢谢!

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    如果死亡层上的碰撞器是触发器,则需要OnTriggerEnter,否则需要OnCollisionEnter。示例:

    private void OnCollisionEnter(Collision collision)
    {
        transform.position = new Vector3(0f, 2f, 0f);
    }
    

    【讨论】:

    • 我应该将什么指定为碰撞?
    • 您在死亡层上添加带有碰撞器的游戏对象。不管是 Box、Sphere 还是 Capsule 对撞机等。
    【解决方案2】:

    您可以向播放器添加碰撞器组件,例如盒子或胶囊碰撞器。在您的脚本中引用它,然后使用onTriggerEnter(Collider collider) 方法。然后你可以在那里设置位置。这是有关onTriggerEnter(Collider collider) 方法的文档。 https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html.

    这里还有一个视频,其用例与您正在做的事情相似https://www.youtube.com/watch?v=ZoZcBgRR9ns。请注意,该视频正在制作 2d 游戏,但同样适用于 3d 但没有“2D”。

    与您的问题无关但认为会有所帮助的是 Unity 的新输入系统。 float x = Input.GetAxis("Horizontal");float z = Input.GetAxis("Vertical"); 已经很老了,新的输入系统更好更容易。我建议你调查一下。还有一件事,建议在FixedUpdate 方法而不是Update() 方法中进行任何物理检查。这将是检查您是否碰撞 (isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);) 并设置速度并移动玩家。您还需要将 Time.deltaTime 更改为 Time.fixedDeltaTimeFixedUpdate() 方法中使用它的任何位置。

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多