首页 > 解决方案 > Unity 脚本错误 CS1061“Vector2”不包含“GetAxis”的定义

问题描述

我在 Unity 中收到的完整错误消息,我正在使用 mac。

Assets/Scripts/Controller.cs(19,45):错误 CS1061:“Vector2”不包含“GetAxis”的定义,并且找不到接受“Vector2”类型的第一个参数的可访问扩展方法“GetAxis”(是您缺少 using 指令或程序集引用?)

这是我正在使用的代码:

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {

public float speed;
private Vector2 moveVelocity;
private Rigidbody2D rigidBody;

void Start() {
    rigidBody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update() {
    Vector2 moveInput = new Vector2(moveInput.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    moveVelocity = moveInput.normalized * speed;
}

void fixedUpdate () {
    rigidBody.MovePosition(rigidBody.position + moveVelocity * Time.fixedDeltaTime);
}
}

如果需要任何其他信息,请告诉我。

标签: unity3dscripting

解决方案


我想你有Input困惑moveInput。此外,如果您有 RigidBody 或 RigidBody2d,您应该尝试不要直接修改 GameObjects 的位置,而是使用该AddForce方法。我会删除固定的更新方法,而是将您的更新方法修改为以下内容:

void Update() {
    Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"));
    rigidBody.AddForce(moveInput.normalized * speed);
}

推荐阅读