1
votes

please help, i'm currently working on a brick breaker game and working on paddle script but it shows error on line 17, i don't know how to change float to vector3

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;
    }
}

here is the script combined both answers

public class Paddle : MonoBehaviour {

    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;
}

}

2
thank you both answers, finally works - S.Y

2 Answers

3
votes

Your error occurs at this line (I guess?):

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

The problem is exactly, what the error message tells you: Input.mousePosition is a Vector3. If you divide a Vector3 by some float, the result is also a Vector3 as this is an element-wise division. As it is still a Vector3 you cannot assign it to a float variable.

To solve this you should either make mousePosInBlocks a Vector3 or choose a component of the vector to assign.

Reference: Input.mousePosition

2
votes

Mathf.Clamp needs a float, not a Vector3.

Change this :

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

To :

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

Same thing for y if needed.

You also need to make mousePosInBlocks a Vector3.

If you only want to process x, keep mousePosInBlocks as a float but replace Input.mousePosition by Input.mousePosition.x