- Home /
audiosource.PlayClipAtPoint only plays once
so i have this game object that is rotating on the y axis, and is constantyl changing speed. i want the object to play a short beep when it makes a full rotation. unfortunately, my scriupt only plays the beep once right when the game starts and then doesnt play it again. what could i be doing wrong? this is unity 5 btw not 4
void Update()
{
transform.Rotate(Vector3.up * (Time.deltaTime * speed));
if (transform.eulerAngles.y == 0)
{
audiosource.PlayClipAtPoint(clip);
}
}
Answer by fafase · Oct 10, 2015 at 01:38 PM
You cannot rely on equality for float due to how the computer store them. 0 is rarely 0 but more likely 0.00000001 which is not 0 for a computer but close enough for a human.
It plays the first round because the value is explicitely set to 0 on start. After that, no more.
You can keep track of the rotation and play when more than 360 (full circle).
private float rotationAngle = 0f;
void Update()
{
float angle = Time.deltaTime * speed;
transform.Rotate(Vector3.up * angle);
rotationAngle += angle;
transform.Rotate(Vector3.up * (Time.deltaTime * speed));
if (rotationAngle > 360f)
{
audiosource.PlayClipAtPoint(clip);
rotationAngle = 0f;
}
}
Answer by Chris-Paul · Oct 10, 2015 at 01:45 PM
That happens because transform.eulerAngle.y is 0 just at the beginning. You need to store the angle separately as a float and add to it when you are rotating, then you check if it reaches 360, so you can set it to 0, here is the code:
float currentAngle;
float speed;
float clip;
void Update() {
float deltaAngle = Time.deltaTime * speed;
currentAngle += deltaAngle; // Keep track of the current angle by adding delta angle to it.
transform.Rotate(deltaAngle * Vector3.up);
if(deltaAngle >= 360) {
currentAngle = 0;
AudioSource.PlayClipAtPoint(clip, transform.position);
}
}
Your answer
Follow this Question
Related Questions
How to restrict rotation properly 2 Answers
20 is not equal to 20 while using Vector3.MoveTowards 2 Answers
How do you combine local and planar translation? 1 Answer
Mathf.SmoothDamp freeking out? 0 Answers