Question by
melvinweert · Sep 30, 2020 at 06:24 PM ·
c#timerpong
C# Pong: How to increase ball speed over time?
So im currently working on a simple Pong game in Unity. I've got everything working out fine so far but I can't seem to figure out how to get the ball speed to increase over time. Here's my script which is attached to the ball:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ballMovement : MonoBehaviour
{
public float speed = 10;
void Start()
{
// Initial Velocity
GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}
float hitFactor(Vector2 ballPos, Vector2 racketPos,
float racketHeight)
{
// ascii art:
// || 1 <- at the top of the racket
// ||
// || 0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "RacketLeft")
{
// Calculate hit Factor
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
// Hit the right Racket?
if (col.gameObject.name == "RacketRight")
{
// Calculate hit Factor
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(-1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
}
}
Comment
Answer by leozhang1 · May 28 at 06:20 PM
what worked for me was (assuming the ball is already moving), I have inside an Update(): rb.AddForce(rb.velocity x speed x Time.deltaTime)
Your answer
![](https://koobas.hobune.stream/wayback/20220613012843im_/https://answers.unity.com/themes/thub/images/avi.jpg)