- Home /
Moving player to the opposite direction of the mouse position
I've already tried to ask this question some days ago but nobody has answered yet, I'll try to ask this again in hope that anyone could help me.
Hello, I've been trying to make it so that my player gets propelled to the opposite direction to where the user makes a mouse click. The following code was applied to the player. I can't get it to work even though the DrawLine debug works and the Debug.log for 2DForceVector works too.
Hopefully you can help me. Thanks in advance.
var movementMaxVelocity : float = 10;
var jumpSpeed : float = 3;
var movementForce : float = 10;
var mouseVectorPosition : Vector2;
var playerVectorPosition : Vector2;
var 2DForceVector : Vector2;
function Update () {
mouseVectorPosition= Camera.main.ScreenToWorldPoint(Input.mousePosition);
playerVectorPosition = transform.position;
2DForceVector = (mouseVectorPosition - playerVectorPosition).normalized;
rigidbody2D.AddForce(2DForceVector * movementForce * -1);
}
Answer by robertbu · Jul 25, 2014 at 04:48 PM
I could not see anything conceptually wrong with your code, so I tried it out. I had to change the name of 2DForceVector since you cannot have a variable starting with a number, and I added a Input.GetMouseButtonDown() to detect a click. The code then worked. The sprite I picked to test it with happened to be a balloon, and the clicking looks good with this sprite.
#pragma strict
var movementMaxVelocity : float = 10;
var jumpSpeed : float = 3;
var movementForce : float = 10;
var mouseVectorPosition : Vector2;
var playerVectorPosition : Vector2;
var ForceVector : Vector2;
function Update () {
if (Input.GetMouseButtonDown(0)) {
mouseVectorPosition= Camera.main.ScreenToWorldPoint(Input.mousePosition);
playerVectorPosition = transform.position;
ForceVector = (mouseVectorPosition - playerVectorPosition).normalized;
rigidbody2D.AddForce(ForceVector * movementForce * -1.0);
}
}
Note if you reverse the order of the subtraction of the vectors on line 12, you will not need the -1 in line 13.
Apparently on the player I was already working on, it didn't work, but making a new sprite and applying the code to it worked. Thanks, now I'll just have to track down the problem with the old sprite.