- Home /
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
Answer by JojoJonas · Apr 03, 2012 at 11:12 PM
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.
I tried changing the following:
transform.position = transform.position - target.rigidbody.position
to:
transform.Translate(transform.position - target.rigidbody.position * Time.deltaTime);
Not only does it still act funny (in terms of going all over), but now it eventually spits out the following console error:
transform.position assign attempt for 'Emerald' is not valid. Input position is { -Infinity, -787959360953950142464.000000, 1426979897156153901056.000000 }. UnityEngine.Transform:Translate(Vector3) GemPickup:Update() (at Assets/Props/Scripts/GemPickup.js:24)
Why is it passing -infinity as a value?