- Home /
Question by
cano543 · Jun 28, 2021 at 03:26 PM ·
scripting problemunity 2dparticlesscripting beginnerparticle system
How can I make particles apeear in exact position?
enter code here
I´m very new to unity and C# and I tried to add particles in my pong game, the problem comes when I try to make the particles appear in the exact position the ball destroys, here is my code if you want to have a look:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scr_Ball : MonoBehaviour
{
public float speed;
public Rigidbody2D rb;
public Vector3 startPosition;
public float hits = 1;
public float Maxhits = 8;
public GameObject effect1;
public GameObject effect2;
void Start()
{
startPosition = transform.position;
Invoke ("Launch", 1);
}
public void Reset()
{
rb.velocity = Vector2.zero;
transform.position = startPosition;
hits = 1;
Invoke ("Launch", 2);
}
private void Launch()
{
float x = Random.Range(0, 2) == 0 ? -1 : 1;
float y = Random.Range(0, 2) == 0 ? -1 : 1;
rb.velocity = new Vector2(speed * x, speed * y);
}
void Update()
{
if (hits>Maxhits)
{
hits = Maxhits;
}
}
float hitFactor(Vector2 ballPos, Vector2 PlayerPos, float PlayerHeight)
{
return (ballPos.y - PlayerPos.y) / PlayerHeight;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "Player 1")
{
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
hits += 0.25f;
rb.velocity = new Vector2(-rb.velocity.x * hits, rb.velocity.y);
}
if (col.gameObject.name == "Player 2")
{
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
hits += 0.3f;
rb.velocity = new Vector2(-rb.velocity.x * hits, rb.velocity.y);
}
if (col.gameObject.name == "P1Goal")
{
foreach (ContactPoint2D contact in col.contacts)
{
Vector2 hitPoint = contact.point;
Instantiate(effect1, new Vector3(hitPoint.x, hitPoint.y, 0), Quaternion.identity);
}
}
if (col.gameObject.name == "P2Goal")
{
foreach (ContactPoint2D contact in col.contacts)
{
Vector2 hitPoint = contact.point;
Instantiate(effect2, new Vector3(hitPoint.x, hitPoint.y, 0), Quaternion.identity);
}
}
}
}
Comment
Where is the code for when your ping pong ball is destroyed?
Your answer
Follow this Question
Related Questions
Is it possible to set one particle system equal to another through script? 0 Answers
How to create a particle system like Absorb power in unity 1 Answer
Laser beam using particle system Unity2d. 0 Answers
How do I change the velocity over lifetime value on a Particle System using a slider? 0 Answers