How to make sine amplitude restricted exactly to given units?

Hi guys, I need help… How to make sine amplitude restricted exactly to given units? For example: if the editor set amplitude to 10, that’s expected to be 10 units going up and down, but the Mathf.Sin() go beyond that (10 units), unlike Mathf.PingPong(). How will I fix that?

I attach a zip file below

Here are my testing scripts:
BulletPattern.cs //make two GameObject and attach this; set one pattern to Sine, and one to Ping Pong.

using UnityEngine;
using System.Collections;

public class BulletPattern : MonoBehaviour {

    public GameObject pingPongBullet;
    public GameObject sineBullet;
    public enum patternType {
        PingPong,
        Sine
    }; public patternType pattern;
    public float amplitude = 10;
    public float frequency = 1;
    private Vector3 movement;
    private GameObject bulletCollector;

    void Start () {
        bulletCollector = GameObject.FindGameObjectWithTag ("BulletCollector");
    }

    void Update () {
        movement = transform.position;

        if (pattern == patternType.PingPong) {
            movement += (Mathf.PingPong ((Time.time * amplitude * frequency) + (amplitude / 2), amplitude) - (amplitude / 2)) * transform.forward;
            Instantiate (pingPongBullet, movement, transform.rotation, bulletCollector.transform);
        } else if (pattern == patternType.Sine) {
            movement += (Mathf.Sin (Time.time * Mathf.PI * frequency) * amplitude) * transform.forward;
            Instantiate (sineBullet, movement, transform.rotation, bulletCollector.transform);
        }
    }
}

Projectile.cs //Make a prefab bullet (small sphere); 1 for Sin, one for PingPong*.*

using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {

    public float speed = 20f;
    // Use this for initialization
    void Start () {
        Destroy (gameObject, 1f);
    }
 
    // Update is called once per frame
    void Update () {
        transform.position += Vector3.left * speed *Time.deltaTime;
    }
}

Thanks for the help… :smile:

3156082–240039–SineAndPingPong.zip (612 KB)

Is there no fix or tricks to do this? Well, I just found out that I just need to multiply sine amplitude to __0.497878__f something to be near perfect to unit length…

Mathf.PingPong:

So it returns a value from 0 to length, in your case amplitude. Which you then subtract amplitude/2 from. Expected results are:

-amplitude/2 → +amplitude/2

Mathf.Sin:

So it returns a value from -1 to 1, which you multiply by amplitude. Expected results are:

-amplitude → +amplitude

So yeah… you get twice the range.

This is normal because that’s the shape of a sine curve, by definition:

Not sure how you landed on multiplying by 0.497878f… 0.5f would suffice, because you are getting twice the range you desire. So halving it would rectify that.

But eh, 0.497 is pretty close to half, so visually speaking it’s roughly the same.

2 Likes