如何将 characterScale.x = -1 替换为 transform。在此上下文中旋转 (0f, 180f, 0f),而不是每帧都执行?

How can I replace characterScale.x = -1 with transform.Rotate (0f, 180f, 0f) in this context, without it being executed every frame?

提问人:HarrisonO 提问时间:7/17/2020 最后编辑:HarrisonO 更新时间:7/17/2020 访问量:27

问:

我对编码视频游戏非常陌生,所以我一直在使用很多在线教程来帮助我制作基本的平台游戏/射击游戏。为了让我的角色能够双向射击,我需要精灵和它的子“FirePoint”来翻转。我怎样才能翻转我的角色,每当水平值 = -1 而没有每帧执行相同的命令时,它都是子角色。

提前致谢!

using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float jumpforce;
    private float moveInput;
    private Rigidbody2D rb;
    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;

    private int extraJumps;
    public int extraJumpsValue;

    public Animator animator;
    void Start()
    {
        extraJumps = extraJumpsValue;
        rb = GetComponent<Rigidbody2D>();
    }
    void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);

        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);


    }
    void Update()
    {
        animator.SetFloat("Horizontal", moveInput);
        if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
        {
            rb.velocity = Vector2.up * jumpforce;
            extraJumps--;
        }
        else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
        {
            rb.velocity = Vector2.up * jumpforce;
        }
        if (isGrounded == true)
        {
            extraJumps = extraJumpsValue;
        }
        Vector3 characterScale = transform.localScale;
        if (Input.GetAxisRaw("Horizontal") < 0)
        {
            characterScale.x = -1;
        }
        if (Input.GetAxisRaw("Horizontal") > 0)
        {
            characterScale.x = 1;
        }
        transform.localScale = characterScale;
    }
}
C# 替换

评论

0赞 Raimund Krämer 7/17/2020
您能否澄清一下您是否想知道如何使用而不是缩放(这似乎是标题所问的),或者您是否主要不想在每一帧上都执行它(这是我从问题文本中理解的)?Rotate
0赞 HarrisonO 7/17/2020
对不起,我不知道这是否是我应该在堆栈溢出时回复的方式。我问的是,在这种情况下,我怎样才能不执行每一帧。Rotate
0赞 Raimund Krämer 7/17/2020
你有理由避免在每一帧上都这样做吗?我之所以问,是因为它是否会导致错误,或者您是否有性能问题,这可能会有所不同。如果出于性能原因,差异可能可以忽略不计。您是否真正想要解决不同的问题,您认为这可能是原因?
0赞 HarrisonO 7/17/2020
@RaimundKrämer 我不希望它激活每一帧,因为它会导致精灵在向左移动时不断来回翻转每一帧。
0赞 Raimund Krämer 7/17/2020
当您设置浮点数时,动画师会做什么?仅从代码中我看不出为什么精灵应该继续来回翻转。也许动画师和代码试图实现同样的事情,这导致了这种行为?如果是这种情况,那么如果不在每一帧都调用它,它可能仍然无法按预期运行。你能添加动画状态机的屏幕截图吗?"Horizontal"

答: 暂无答案