- Home /
Moving Player
Please tell me how to make the object move like in the picture. Circle - where the player pressed the mouse button. Red square - where the player released the mouse. Arrow - where the object should fly.
I need the code to work like this: clicked on the mouse button, chose the direction, let's say it up, let it go and it flew in the opposite direction, that is, to the left. If I released in the upper right corner, then poltelel in the lower left corner
By itself this code works, but the object does not fly down, but somewhere to the left.
if (Input.GetMouseButton (0)) {
if (GameObject.Find ("Player(Clone)") == null) {
Instantiate (player); // Создаём игрока
}
firstPos = pl.transform.position; // Получаем первую позицию
Vector2 camPos = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));
pl.transform.localPosition = camPos; // Перетаскиваем игрока мышкой
Debug.Log(twoPos);
}
if (Input.GetMouseButtonUp (0)) {
twoPos = pl.transform.position; // Получаем вторую позицию игрока
twoPos *= -1; // Умножает на -1, чтобы потом игрок полетел в противоположную сторону.
twoPos = transform.TransformPoint(twoPos);
pl.AddForce (twoPos * 50);
Answer by MT369MT · Jul 29, 2018 at 01:37 PM
Hi, if I understand right you are trying to do something like the angry birds shoot. I tried to modify your script so:
if (Input.GetMouseButtonDown(0))
{
firstPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
twoPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (firstPos - twoPos);
pl.AddForce(direction * 50);
}
Hi. This script works correctly only if you press in the center of the map, but if you press and shoot in the left corner somewhere, it flies to the left in independence where the ball was directed
I want to do this: clicked the mouse button and the player (ball) appeared and if I want to make it fly down, then move the player up and release the mouse button and it starts to fly down. But if I want to make it fly up, then move the player down and let it go and it should fly upwards
Your answer
Follow this Question
Related Questions
How do i prevent the player from dragging a ui element off screen? 1 Answer
MoveTowards problem 1 Answer
What am I doing wrong? 1 Answer
Hello everyone, I would like to create a Geometry dash like triangle Transporter in unity. 0 Answers
How do I change Raycast's direction based on movement input? 1 Answer