0

So, I want to make a game where the player can click on different objects and be pulled towards them. To achive this, I used this code:

void FixedUpdate () 
 {
     if(Input.GetMouseButton(0))
     {
     // Move the player
     Rigidbody2D playerRigBod2D = thePlayer.GetComponent<Rigidbody2D>();
     playerRigBod2D.AddForce(transform.position - thePlayer.transform.position);

     // Draw a line towards the player
     GetComponent<LineRenderer>().SetPosition(1, thePlayer.transform.position);    
     }
 }

This works fine with just one object of this prefab, but once I add more, the player gets pulled to the point in between these objects. I can't quite make out why, since transform.position should be unique to each of the objects that have this script applied right?

I'd be thankful if one of you could shed some light on this, thank you :)

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Is this script on each of the prefabs? – Matt L. Aug 17 '17 at 15:40
  • `Input.GetMouseButton` is used to detect mouse click **not** mouse click on an object. Detecting click on an object requires a raycast or the unity eventsystem(recommded). – Programmer Aug 17 '17 at 15:45

1 Answers1

1

When you are clicking, every object with this script attached is detecting if(Input.GetMouseButton(0)) as true, and are therefore all applying a force to the player at the same time - leaving the end position as an average.
You will need to add a qualifier that detects when the player is clicking on the specific object, instead of clicking in general.

ryeMoss
  • 4,303
  • 1
  • 15
  • 34
  • Correct. If you're trying to detect that the object was clicked, the easiest (but not very flexible) way would be to implement [OnMouseUp](https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUp.html). – apk Aug 17 '17 at 15:44
  • Thanks very much! I want the pull to happen while the mouse button is held down, so I think I will implement a bool that is set to true in OnMouseDown and to false in OnMouse Up – Claudius Goennus Aug 17 '17 at 19:53