- Home /
move a sprite where the player has clicked in a 2D top view
Hello, I would like to move a sprite where the player has clicked. It would be a mouvement like in Spore but with 2D sprites (cell) Spore
I usaly code in Javascript, do you have an idea to do that? I have tested many scripts but they don't work with the new sprite system of unity 4.3.
Thank you
P.S: Sorry for my english, it's not my native langage.
Any number of existing script posted to UA should have worked. What one(s) did you try? And what do you want to happen once the object has reached the last click position...keep going or just stop?
The sprite do not move at all. Like if the functions used to move it were not effective.
So how do you want to move the sprite...using the transform, or using Rigidbody2d? And again, what do you want to happen once the object reaches the point clicked. Should it stop, or should it keep going in the same direction.
It should stop. I would like it to face the direction and go where I have clicked. Or to go to my mouse when I drag my mouse. (like in the video link I put) Thanks
Answer by robertbu · Dec 26, 2013 at 07:52 PM
Here is a bit of code that moves and rotates. It assumes that the camera is axes aligne and that it is facing towards positive 'z':
#pragma strict
public var speed = 1.5;
public var rotationSpeed = 90.0;
private var pos : Vector3;
private var qTo : Quaternion;
function Start () {
pos = transform.position;
qTo = transform.rotation;
}
function Update () {
if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) {
pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
}
var dir = pos - transform.position;
if (dir != Vector3.zero) {
qTo = Quaternion.FromToRotation(transform.right, dir) * transform.rotation;
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, Time.deltaTime * rotationSpeed);
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
I just noticed that your title says 'Top view'. Is your camera looking down the 'Y' axis rather than the default setup for a 2D game?