0

I'm currently working on a simple baseball game. What I'm trying to do is have the player be able to swing the bat backwards to "charge up" power, so to speak, and then when a button is released he will swing the bat forward at a speed equal to the amount of power stored up.

This is all well and good, but my problem is I need to stop the motion of the bat when he reach a certain point on the y-axis, and I'm a bit unsure how to go about doing this as I cannot just tell it to stop rotating after a set time as the bat won't reach the front point at the same time every time due to the difference in speed each swing might have.

What I'm trying to do basically is something like if(reached 266 on the y-axis stop rotating), but I'm unsure of how to do this.

Anyway here is the code I've written so far:

public int rotateSpeed = 50;
public float AmountOfPowerChargedUp = 0;

void Update() 
{

    if (Input.GetMouseButton(0))    
    {
        AmountOfPowerChargedUp += 5f;
        transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime); 
        Debug.Log(AmountOfPowerChargedUp);
    }

    if (!Input.GetMouseButton (0)) 
    {
        transform.Rotate(Vector3.down * AmountOfPowerChargedUp * Time.deltaTime);
    }   

}

private void OnGUI()
{
    GUI.Label (new Rect (50, 15, 250, 25), "AmountOfPowerChargedUp: " + AmountOfPowerChargedUp); 
}
LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
  • I dont know unity that well, but isnt there an event called something like "move" which you can subscribe to, and then in the method body test if the new position is acceptable something like if (object.positoon.Y){<<>>} – Rasmus Damgaard Nielsen Jul 09 '15 at 06:07

1 Answers1

0

if your rotating a certain amount of degrees, you should use a Slerp or RotateTowards

Vector3 targetDir = (target.position - transform.position).normalized;

// The step size is equal to speed times frame time.
float step = speed * Time.deltaTime;

Vector3 newDir = Vector3.RotateTowards(transform.up, targetDir, step, 0.0);

transform.rotation = Quaternion.LookRotation(newDir)
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
  • The problem is im not rotating the same amount of degrees every time, it depends how far back the baseball bat has been pulled so i cant do it like that, also i cant use time to measure it either because the speed of the forwardswing varies also. Im at a loss here –  Jul 09 '15 at 00:08
  • Cant use time to measure it? What are you talking about? you want to use time whenever you are doing an iterative call on a movement. Also what you want to do is a Slerp i already said that, it will do exactly what you are trying to do. Just do a Slerp from any current rotation to the end rotation your looking for, that way you aren't rotating the same amount of degrees every time but the exact amount you need. – maraaaaaaaa Jul 09 '15 at 01:36