- Home /
Vector3 x start position doesn't work properly
The code is assigned to the paddle in a block breaker game.
void Update () {
Vector3 paddlePos = new Vector3(0f, this.transform.position.y, 0f);
float mousePosInBlocks = Input.mousePosition.x / Screen.width * 12;
print(mousePosInBlocks);
paddlePos.x = mousePosInBlocks;
this.transform.position = paddlePos;
}
Whatever I set to the x value: 0f, -5f or this.transform.position.x, the paddle always starts from the left side (5f). It ignores coordinates I've inputted in unity (when there's a this.transform.position.x in a code) or this 0f coordinates I've set. How to make the paddle start in the middle (0f)?
Thanks in advance!`enter code here`
From the scripting reference for Input.mousePosition
"The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height)."
So the calculation for mousePosInBlocks
will give you 0 when the mouse is on the left, and 12 when the mouse is on the right. If you want the paddle to be in the centre when the mouse is in the centre, subtract 0.5f before you multiply with 12 : float mousePosInBlocks = (Input.mousePosition.x / Screen.width - 0.5f) * 12;
I'm not sure why the calculation doesn't affect the position, it should modify it. Is there maybe another script or component on the object that would modify the position of the paddle?
BTW, you can simplify the code to this:
private void Update () {
float mousePosInBlocks = ... // do here your calculation
print (mousePosInBlocks);
transform.position = new Vector3(mousePosInBlocks, transform.position.y, 0);
}
Answer by hectorux · Jun 25, 2018 at 11:48 AM
Try this (it will be more eficent, and also i think it solves your problem):
public float screeonOfssetWithWorld;
void Update () {
float mousePosInBlocks = Input.mousePosition.x / Screen.width * 12-screeonOfssetWithWorld;
print(mousePosInBlocks);
paddlePos.x = mousePosInBlocks;
this.transform.position = new Vector3(mousePosInBlocks, this.transform.position.y, 0f);
}