D
D
Dima Klepko2022-01-06 20:58:46
Unity
Dima Klepko, 2022-01-06 20:58:46

Why doesn't the player's position change?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class circle : MonoBehaviour
{

    bool MouseDown = false;

    Vector3 posPlayer;

    void Start()
    {
        posPlayer = GetComponent<Transform>().position;
    }

    void onMouseDown()
    {
        MouseDown = true;
    }

    void onMouseUp()
    {
        MouseDown = false;
    }

    void Update()
    {
        Vector2 Cursor = Input.mousePosition;
        Cursor = Camera.main.ScreenToWorldPoint(Cursor);


        if(MouseDown)
        {
          posPlayer = Cursor;
        }
    }
}


For some reason the code does not work, although I look and see no errors

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
Uncle Bogdan, 2022-01-06
@motkot

position is not a reference type.
Do this:
posPlayer.position = Cursor

N
Nekit Medvedev, 2022-01-10
@NIKROTOS

and so, if the LMB is pressed, then the cursor coordinates are equal to a variable that stores 3 values ​​(not the current coordinates, but the values).
If the left-click is not pressed, then the cursor is created , after which, it is set to Input.mousePosition, which is the deviation from the screen angle in pixels). After that, this deviation is converted into coordinates.

Vector2 Cursor = Input.mousePosition;
        Cursor = Camera.main.ScreenToWorldPoint(Cursor);
    if(MouseDown)
        {
          posPlayer = Cursor;
        }

//логичней будет сделать так
public  Vector2 Cursor;//публичные переменные принято писать с заглавной буквы

    void Update()
    { 
          if(MouseDown)
        {
          posPlayer = Camera.main.ScreenToWorldPoint( Input.mousePosition);
        }
    }

It would be even more logical to get a link to a specific object or component, how to do it, see here. https://habr.com/en/post/128711/
In the code I wrote, I didn't do it because I haven't touched the unit for a long time and I don't remember exactly how it's written.

R
RandomProgrammer, 2022-01-10
@RandomProgrammer

Cursor is a unity class. I do not think that the error is due to this, but it seems to me that it is better to name the variable differently.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question