- Home /
Setting my position to the position of a gameobject
I'm trying to make a farming game thing and I want to move my seeds to a gameobject above my crop plot. What I want to accomplish: when I'm moving the seeds and I collided with the crop plot and when I release my mouse button it sets my position to the gameobject above the crop plot. It isn't working and I can't seem to figure out why . So here is the code thanks in advance :)
 private float startPosX;
 private float startPosY;
 private bool moving;
 public Transform cropPlotAbove;
 public Transform myTransform;
 void Start()
 {
     myTransform = GetComponent<Transform>();
 }
 void Update()
 {
     if (moving)
     {
         Vector3 mousePos;
         mousePos = Input.mousePosition;
         mousePos = Camera.main.ScreenToWorldPoint(mousePos);
         this.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.transform.localPosition.z);
     }
 }
 private void OnMouseDown()
 {
     if (Input.GetMouseButton(0))
     {
         Vector3 mousePos;
         mousePos = Input.mousePosition;
         mousePos = Camera.main.ScreenToWorldPoint(mousePos);
         startPosX = mousePos.x - this.transform.localPosition.x;
         startPosY = mousePos.y - this.transform.localPosition.y;
         moving = true;
     }
 }
 private void OnMouseUp()
 {
     moving = false;
 }
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if(moving == true && collision.gameObject.tag == ("Crop Plot") && Input.GetMouseButtonUp(0))
     {
         myTransform.transform.position = cropPlotAbove.transform.position;
     }
 }
Please when you post code - click on the binary numbers 101 010 at the top and then it opens a block into which you can copy and paste your code.
Your using Vector2 and Vector3 - but I assume from the Collision2D that you're doing a 2D game.
You would need to convert your mouse position to a vector 2 - you can do this:
         if (Input.GetMouseButtonDown(0))
         {
             Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
             Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);
            }
 
Then you'd probably have to do some functions in void update -
- If user clicks on the seed set bool moving to true. 
- If bool moving is on always set the seed's transform to mousePos2D. 
- If there is a collision and bool moving is on, set bool moving to false and move the seed to the position of the collision object. 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                