- Home /
How to get click position in Vector 2 ?
In my 2D game, I want to move my player (sprite) to the click location, by Lerp or MoveTowards. I actually may know how to use Lerp or MoveTowards, but can someone help me on finding these coordinates ? I tried a lot of things, like function OnMouseDown, Raycast etc. but I couldn't make it work properly. I work in javascript.
Answer by RedHedZed · Jan 16, 2015 at 06:57 PM
You can use Input.mousePosition to get the mouse coordinates and save them to a Vector2. You can then use Camera.ScreenToWorldPoint to convert those coordinates to world space in order to Lerp your player.
Thank you for the comment, I tried it but it seems not to work. I tried with both GetButtonDown("Fire1") and Get$$anonymous$$ouseButtonDown(0):
#pragma strict
var speed : float = 2f;
public var worldPos:Vector3;
public var target : Transform;
public var cameraloc:Camera;
function Start () {
}
function Update () {
var mousePos:Vector3;
cameraloc = GameObject.Find("Camera").GetComponent(Camera);
mousePos = Input.mousePosition;
worldPos = cameraloc.ScreenToWorldPoint(mousePos);
}
if (Input.GetButtonDown ("Fire1")) {
Debug.Log("$$anonymous$$ove!");
transform.position = Vector3.$$anonymous$$oveTowards(target.position, worldPos, speed);
}
That if statement is never reached (you placed it outside of the Update function). And since you only care when the button is pressed, you can move the logic for getting the mouse position inside of the if statement as well.
Yes, you are right, I missed that one. $$anonymous$$now my object moves but not how I want. When I click, the object teleports (doesn't move how it is supposed to from $$anonymous$$oveTowards) for a portion of the length. So, If I click 5 times on my location, only then the object will reach it. What now ? I will paste the current update of the code:
#pragma strict
var speed : float = 2f;
public var worldPos:Vector2;
public var target : Transform;
public var cameraloc:Camera;
function Start () {
}
function Update () {
var mousePos:Vector2;
cameraloc = GameObject.Find("Camera").GetComponent(Camera);
mousePos = Input.mousePosition;
worldPos = cameraloc.ScreenToWorldPoint(mousePos);
if (Input.GetButtonDown ("Fire1")) {
Debug.Log("$$anonymous$$ove!");
transform.position = Vector3.$$anonymous$$oveTowards(target.position, worldPos, speed);
}
}
Because that's what you've written - "when the mouse button is clicked, move 2 units in the direction of the target". What did you mean to happen?
Your answer
Follow this Question
Related Questions
Moving 2D sprite along a path 0 Answers
Find cardinal direction of collision based on 2D Cartesian coordinates 1 Answer
conserve momentum of vector3.moveTowards in 2D game 0 Answers
Moving an UI element from point A to point B 1 Answer
My vector2.movetowards is 2-3x faster when trigger off and trigger on collider collides 0 Answers