You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数报错:Invalid operands 'float' and 'Vector2' in operator '!=' 求助解决

问题解决:Invalid operands 'float' and 'Vector2' in operator '!='

错误根源

你遇到的类型不匹配错误,是因为move函数的motion参数实际接收了float类型的值,但代码里把它当作Vector2来比较和访问x/y属性,导致类型兼容问题。

解决步骤

  1. 检查函数调用方式
    确保调用move时传入的是Vector2类型的方向向量,比如通过输入获取的完整向量:
# 示例调用:获取上下左右输入组成的Vector2
var input_dir = Input.get_vector("left", "right", "up", "down")
move(input_dir)

避免直接传入单个轴的float值(比如Input.get_axis("left", "right"))。

  1. 规范函数参数与逻辑
    给参数添加类型注解,同时纠正atan2的参数顺序(Godot中atan2需传入(y, x)才能得到正确角度),用Vector2.ZERO替代Vector2()更规范:
func move(motion: Vector2):
    if motion != Vector2.ZERO:
        target_angle = atan2(motion.y, motion.x) - PI/2
        Skin.set_rot(target_angle)
  1. 兼容异常输入(可选)
    如果确实需要处理可能传入的float值,可以先做类型判断与转换:
func move(motion):
    if typeof(motion) == TYPE_FLOAT:
        # 这里假设float对应x轴方向,可根据需求调整为y轴
        motion = Vector2(motion, 0)
    if motion != Vector2.ZERO:
        target_angle = atan2(motion.y, motion.x) - PI/2
        Skin.set_rot(target_angle)

内容的提问来源于stack exchange,提问作者dude_in_a_basement

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:15:17