So Iam training my Unity C# skills and Iam creating small copy of the game Pong but when I ran it, the ball (it’s actually a cube) has different speed everytime when I start the game and I don’t know where is the problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cube : MonoBehaviour
{
public float cubeSpeed = 10f;
float directionX;
float directionY;
void Start()
{
directionX = Random.Range(-8f, 8f);
directionY = Random.Range(-4f, 4f);
GetComponent<Rigidbody>().AddForce(new Vector3(directionX, directionY) * cubeSpeed);
}
void Update ()
{
}
}
The reason is because your direction vector can have a magnitude or length which is greater than or less than 1, which when multiplied by your cubeSpeed will increase or decrease the cube speed. What you need to do is normalize the value of your direction before multiplying by speed so that it has a vector length of 1, and the speed will remain constant when multiplied by it.
new Vector3(directionX, directionY).normalized * cubeSpeed