Move with the ball and bounce the ball Unity2D
Move with the ball and bounce the ball Unity2D:
C#:
1.insland:
[SerializeField] Transform ball;
Rigidbody2D rb;
[SerializeField] float jumfore =4;
[SerializeField] float speed;
void Start()
{
this.rb = GetComponent<Rigidbody2D>();
}
void Update()
{
float distanceFromBall = this.ball.position.x - this.transform.position.x;
this.transform.Translate(new Vector2(distanceFromBall,0f));
}
private void OnTriggerStay2D(Collider2D other) {
if(other.GetComponent<ball>())
{
if(other.attachedRigidbody.velocity.y <=0)
{
Rigidbody2D rb = other.GetComponent<Rigidbody2D>();
if(rb != null)
{
Vector2 velocity = rb.velocity;
velocity.y = jumfore;
velocity.x += jumfore * Mathf.Sin(Time.time*speed);
rb.velocity = velocity;
}
}
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.GetComponent<ball>())
{
if(other.attachedRigidbody.velocity.y <=0)
{
Rigidbody2D rb = other.GetComponent<Rigidbody2D>();
if(rb != null)
{
Vector2 velocity = rb.velocity;
velocity.y = jumfore;
velocity.x += jumfore * Mathf.Sin(Time.time*speed);
rb.velocity = velocity;
}
}
}
}
Post a Comment