So currently when someone score the ball move back to the center but keeps moving,
I want it so that when it respawn the ball is stuck in the center for like 2s before moving again but can’t
seem to figure out how to.
Here’s my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ballMovement : MonoBehaviour
{
public float speed = 5;
public float respawnspeed = 5;
public float acceleration = 1;
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 Update()
{
//Add acceleration to speed, make sure it's not above topSpeed)
speed += Time.deltaTime * acceleration;
}
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;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Goal")
{
speed = respawnspeed;
Update();
}
}
}