error CS1503: Argument 2: cannot convert from ‘UnityEngine.Vector2’ to ‘float’

huangapple go评论77阅读模式
英文:

error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector2' to 'float'

问题

以下是代码的翻译部分:

我正在按照侧滚游戏移动脚本的教程进行操作,但遇到了这个错误:“error CS1503: 参数 2:无法将 'UnityEngine.Vector2' 转换为 'float'”

这是代码,我认为问题可能出在 FixedUpdate,但我不太确定:

请注意,我已经将代码中的HTML实体编码(如"&<)还原为正常的代码文本。

英文:

i'm following a tutorial for the movement script for my sidescroller game but i encountered this error "error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector2' to 'float'"

this is the code, i suppose the issue is in FixedUpdate but i'm not sure

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Movement : MonoBehaviour
{
    private float horizontal;
    private float speed = 8f;
    private bool isFacingRight = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }
}

答案1

得分: 0

在FixedUpdate中,您试图将Vector2的y分量设置为一个Vector2,而应该是一个float。

private void FixedUpdate()
{
    rb.velocity = new Vector2(horizontal * speed, rb.velocity);
}

很可能您的意思是这个:

private void FixedUpdate()
{
    rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}

在这里,您设置了速度的y部分为旧速度的y部分,保持不变。rb.velocity.y是一个float,而新的Vector2需要两个float。
希望这有所帮助!

英文:

In FixedUpdate you are trying to set the a vector2 y component to a Vector2, while it should be a float.

private void FixedUpdate()
{
    rb.velocity = new Vector2(horizontal * speed, rb.velocity);
}

Most likely you were meaning this:

private void FixedUpdate()
{
    rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}

Here you set the y part of the velocity two the y part of the old velocity, leaving it the same. Here rb.velocity.y is a float and a new Vector2 takes two floats.
Hope this helps!

huangapple
  • 本文由 发表于 2023年3月7日 00:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定