Unity横版游戏移动脚本报错CS1503:无法将Vector2转换为float
解决Unity横版移动脚本的CS1503错误
错误error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector2' to 'float'的原因很明确:你在FixedUpdate方法中创建Vector2时,第二个参数传了整个rb.velocity(Vector2类型),但new Vector2的第二个参数要求是float类型,类型不匹配导致报错。
修正方案
把FixedUpdate里的代码修改为:
private void FixedUpdate() { rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); }
说明
rb.velocity.y是Rigidbody2D当前速度的y轴分量,属于float类型,刚好符合new Vector2的参数要求。这样修改既解决了类型错误,还能保留角色竖直方向的原有运动状态(比如下落、跳跃的速度不会被重置),不影响后续的跳跃等逻辑。
完整修正后的代码
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.y); } private void Flip() { if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) { isFacingRight = !isFacingRight; Vector3 localScale = transform.localScale; localScale.x *= -1f; transform.localScale = localScale; } } }
内容的提问来源于stack exchange,提问作者bald_man_
相关产品推荐
相关产品推荐

