In-game pickup not moving towards player after being collected

Hi guys,

I have some pickups in my game, which are supposed to move towards the player after being picked up. Here is GemPickup.js:

`
#pragma strict

var scoreValue : int = 1;

private var target : GameObject;

private var pickedUp = false;

function Start () {
	target = GameObject.FindGameObjectWithTag("Player");
}

function OnTriggerEnter (other : Collider) {
    // Make it go towards the penguin and disappear
    pickedUp = true;
    Debug.Log("Gem collected!");
}

function Update () {

	if (pickedUp)
	{
		// Move the gem towards the player
		transform.position = transform.position - target.rigidbody.position * Time.deltaTime;
		Debug.Log("Moving gem to player...");
		//Remove from game environment after being collected
		//TODO: Add scoring system
		if (transform.position == target.rigidbody.position)
		{
			Destroy(this);
			Debug.Log("Add score");
			//TODO: take scoreValue and add it to the player's score
		}
	}
}
`

The OnTriggerEnter() code works just fine, since the the debug log message gets printed. However, although the fact of getting picked up is being detected in Update(), the gems just never seem to meet the player, preferring to move in bizzare directions instead. What gives?

MachCUBED

1 Answer

1

It’s this line if I’m not mistaken:

transform.position = transform.position - target.rigidbody.position

You shouldn’t be setting transform.position to the difference here; you should use Translate().

For example, if your player was at 10, 0, 10, and your object was at 15, 0, 15, then your computed value (that you’re plugging into transform.position) would be 5, 0, 5. That’s why your object is bouncing around everywhere.