Search code examples
c#unity-game-engineendlessscroll

add score by distance


I currently learn unity3d and start to create an endless game, and I want to add score by a distance that player has traveled on + x axis, so I want to calculate only how far the player traveled on + x axis.. how to calculate it?

this is my scripts

public class Score : MonoBehaviour
public float distance;
public Transform player;
private float score = 0f;
public Text scoreText;

void Awake()
{
    distance = Vector3.Distance(player.position, transform.position);
}


void Update()
{
    if (distance > player.transform.position.x)
    {
        score = distance ++;
        scoreText.text = distance.ToString();
    }
}

}


Solution

  • You can have something like this to get you started. I set it to 0.1 distance to get +1 score but that number can be anything of course.

    private const float DISTANCE_REQUIRED_FOR_1_POINT = 0.1f;
    private Vector3 previousPlayerPosition;
    private float distanceSinceLastScore;
    
    public Transform player;
    private float score = 0f;
    public Text scoreText;
    
    void Awake()
    {
        //At the start save the start position.
        previousPlayerPosition = player.position;
    }
    
    
    void Update()
    {
        //Calculate the distance travvelled since last update.
        distanceSinceLastScore += player.position.x - previousPlayerPosition.x;
        //Set the previous position the current.
        previousPlayerPosition = player.position;
    
        int scoreToAdd = 0;
        while (distanceSinceLastScore > DISTANCE_REQUIRED_FOR_1_POINT)
        {
            //Calculate how many points to add in this update. (Likely always 1 or none)
            ++scoreToAdd;
            distanceSinceLastScore -= DISTANCE_REQUIRED_FOR_1_POINT;
        }
    
        if (scoreToAdd > 0)
        {
            score += scoreToAdd;//Add to the total score.           
            scoreText.text = score.ToString();//refresh the text display.
        }
    }