0
\$\begingroup\$

I writing a script that would make my players reach a target destination. It looks like this so far:

private void MoveTowardsGoal() {
    if (Vector3.Distance (reachGoalTarget.transform.position, transform.position) > 2.0f) {
        rDirection = (reachGoalTarget.transform.position - transform.position).normalized;
        if (rAcceleration < rMaxSpeed) {
            rAcceleration += 0.5f;       
        }
        rVelocity = rDirection * Time.deltaTime * rAcceleration;
        transform.Translate (rVelocity,Space.World);
    }
}

It works fine: The objects move towards the destination point. However, I want them to move looking at the target in the forward direction (forward z axis). Currently they move with their x axis facing front.

I tried a simple rotation inside Start() like transform.LookAt(reachGoalTarget.transform). With this, they look in the forward direction but then they completely move off their initial positions by rotating themselves to reach the goal.

What am I doing wrong?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What does this mean? "they completely move off their initial positions by rotating themselves to reach the goal". You mean the objects are not rotating around the correct center? Have you tried putting the LookAt code in the update method instead of the start method? \$\endgroup\$
    – House
    Sep 10, 2014 at 5:25
  • 1
    \$\begingroup\$ Given the solution he found (his deleted answer says "I increased the target size and it worked") I'm voting to close this question. There is no useful information here. \$\endgroup\$
    – jhocking
    Mar 11, 2015 at 13:02

1 Answer 1

1
\$\begingroup\$

The function Start is executed only once, when the script is first activated. It doesn't get called over and over again like Update(), that's why the LookAt doesn't work. Try putting a transform.LookAt inside the MoveTowardsGoal function and check for the objects position, if it reaches its goal revert the rotation back to its original.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Well, if the goal never moves, this shouldn't be the problem. \$\endgroup\$
    – Ben
    Sep 10, 2014 at 6:57
  • \$\begingroup\$ Yes, that is true. I gave my suggestion assuming that he wants the object to face the goal only while it is moving towards it and not otherwise. \$\endgroup\$ Sep 10, 2014 at 7:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .