关于c#:unity 5.3.0f4错误CS0029;无法将类型’UnityEngine.Vector3’隐式转换为’float’

unity 5.3.0f4 error CS0029;cannot implicitly convert type 'UnityEngine.Vector3' to 'float'

请帮忙,我目前正在从事破砖游戏,并正在使用桨脚本
但它在第17行显示错误,我不知道如何将float更改为vector3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using UnityEngine;
using System.Collections;

public class Paddle : MonoBehaviour {


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);

        float mousePosInBlocks = Input.mousePosition / Screen.width * 16;

        paddlePos.x = Mathf.Clamp(mousePosInBlocks, 0.5f, 15.5f);

        this.transform.position = paddlePos;
    }
}

这是结合了两个答案的脚本

公共班级桨:MonoBehaviour {

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    Vector3 mousePosInBlocks;
    Vector3 paddlePos;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);

    mousePosInBlocks = Input.mousePosition / Screen.width * 16;

    paddlePos.x = Mathf.Clamp(mousePosInBlocks.x, 0.5f, 15.5f);

    this.transform.position = paddlePos;
}

}


您的错误发生在此行(我想是吗?):

1
float mousePosInBlocks = Input.mousePosition / Screen.width * 16;

问题恰好是错误消息告诉您的内容:Input.mousePositionVector3。 如果将Vector3除以某个浮点数,则结果也是Vector3,因为这是逐元素的除法。 由于它仍然是Vector3,因此无法将其分配给float变量。

为了解决这个问题,您应该将mousePosInBlocks设置为Vector3或选择要分配的向量分量。

参考:Input.mousePosition


Mathf.Clamp需要浮点数,而不是Vector3。

改变这个:

1
 paddlePos.x = Mathf.Clamp(mousePosInBlocks, 0.5f, 15.5f);

至 :

1
paddlePos.x = Mathf.Clamp(mousePosInBlocks.x, 0.5f, 15.5f);

如果需要,对y也是一样。

您还需要将mousePosInBlocks设置为Vector3。

如果只想处理x,请将mousePosInBlocks保留为浮点数,但将Input.mousePosition替换为Input.mousePosition.x