D
D
Daniel Petrov2017-03-24 11:02:04
C++ / C#
Daniel Petrov, 2017-03-24 11:02:04

Controller in C#, Unity3d. What am I doing wrong?

Good afternoon!
I started to study units and decided to start with a simple little mini-game.
The bottom line is: there is a rocket, it "flies" up to infinity. It is necessary to organize the control of this rocket as follows: In any place on the screen, wherever I click and move the cursor, the rocket must repeat the cursor movement, i.e. move in sync with it.
What do I have:

void OnMouseDown()
    {
        startPoint = Input.mousePosition;
        clicked = true;
        
    }
    void OnMouseUp()
    {
        clicked = false;
    }

When pressed, I read the cursor coordinate and change the boolean variable.
After that, in Update:
if (clicked) {

            endPoint = Input.mousePosition;
            aimPoint = (endPoint - startPoint);

            TheRocket.transform.position = Camera.main.ScreenToWorldPoint(TheRocket.transform.position + aimPoint)/2;
}

As a result of this code, everything works, the rocket repeats the movements of the cursor, but every time I click on the screen, the rocket rises to the lower left corner at the same coordinates. Always.
I will be very grateful for the help, friends!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Basmanov, 2017-03-24
@CR33PY

TheRocket.transform.position is the world coordinates of the rocket. Input.mousePosition is two-dash coordinates in the screen plane. Using Camera.main.ScreenToWorldPoint you project two-dash coordinates onto the plane in front of the camera, the distance to which is determined by the z-coordinate in the passed parameter.
Thus, if you do not want to teleport the rocket to the clicked location, then you need to calculate the delta of the cursor movement compared to the previous frame in world coordinates. First, get the distance of the rocket plane to the camera using Camera.WorldToScreenPoint , then in each frame move the cursor to world coordinates using ScreenToWorldPoint and read the vector from the previous position to the current one. The resulting vector is simply added to the position of the rocket.

G
GreatRash, 2017-03-24
@GreatRash

There is an opinion. that the mouse position is given to you in screen coordinates, you first need to convert them to world coordinates, and then work with them.

endPoint = Input.mousePosition;
endPoint = Camera.main.ScreenToWorldPoint(endPoint);

But the position of the rocket is already in world coordinates. so it doesn't need to be stuffed in ScreenToWorldPoint.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question