Hi all! I am trying to make a script that lauches the ball towards the mouse rather then in a given direction.
I want it lanched at a set speed towards the mouse pointer (meaning that if you try to hit a target far away, gravity will make you miss slightly and speed will not be higher because mouse is far away).
Normally you do this with a Vector2 mousePos - a Vector2 paddlePos and Normalize the result, the problem is that this game is in game units, not in coordinate form, and thus I just cannot get my paddle to hit.
My code yet is this:
public Vector2 getDirection () {
Vector2 paddlePosition = new Vector2(this.transform.position.x,this.transform.position.y);
Debug.Log ("paddleposition is " + paddlePosition.x + " " + paddlePosition.y);
float mousePosX = (Input.mousePosition.x / Screen.width) * 16;
float mousePosY = (Input.mousePosition.y / Screen.height) * 8; //does not work better with 12 as 1,33 ratio should indicate
Debug.Log (mousePosX + " " + mousePosY);
Vector2 mousePosition = new Vector2(mousePosX,mousePosY);
//mousePosition.Normalize();
Vector2 returnValue = mousePosition-paddlePosition;
returnValue.Normalize();
//Debug.Log (mousePosition.x + " " + mousePosition.y + " is mousePos");
Debug.Log ("Returnvalue = " + returnValue.x + " " + returnValue.y);
return(returnValue);
}
This code works for aiming almost correctly as long as the paddle is centered, but is waay of the mark if I place the paddle on the sides. The code used to call the method is this:
if (Input.GetMouseButtonDown(0)) {
if (!paddle.canMove) {
//This code launches the ball from given paddlePos, reactivate paddle and starts the game
Vector2 direction = paddle.getDirection();
direction = direction;
this.rigidbody2D.velocity = direction*10;
paddle.canMove = true;
hasStarted = true;
}
else if (!hasStarted){
// This code locks the paddle to where you want to launch from
AudioSource.PlayClipAtPoint(startSound,transform.position);
paddle.canMove = false;
}
}
The game is designed as tutorial standard to fit a 800/600 window. Please help me, this is not my strong side!
I suspect my error might be in the y direction since the below script works perfectly (or I might just be completly off somewhere)
I use this script to adjust paddle to game window, and it works perfectly for all paddle sizes:
float boundsSize = this.transform.lossyScale.x / 2;
mousePosInBlocksX = Mathf.Clamp(((Input.mousePosition.x / Screen.width)*16),boundsSize,16f-boundsSize);
Vector3 paddlePos = new Vector3(mousePosInBlocksX,this.transform.position.y,0f);
this.transform.position = paddlePos;