I have slingshot function in my game (think Angry Birds) and I have set it up so that the character in the slingshot can only be pulled back a certain distance. However, the launch function that adds force to the character on launch follows the position of the mouse. In other words, when I click on the character and pull it back, I can pull it to a set distance away from it’s starting point. But I can continue moving the mouse further away from the starting point, adding even more force, so when I release, the character flies much farther than they should. The launch code is using Vector3s to get the position, but Clamp.Magnitude uses the radius variable which is a float. Here’s the code I have so far:
function Update()
{
//Raycast checks to see if squirrel is clicked on
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 100))
{
if(hit.transform.tag == "squirrel")
{
//gets mouse point in world space
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0; //makes sure Z = 0
//drag squirrel while button pressed
if(drag)
{
//Positions squirrel at the mouse's location
transform.position = pos;
}
if(Input.GetMouseButtonDown(0))
{
drag = true;
startPos = pos; //save initial position
wasClicked = true;
}
}//Closes if(hit.transform.tag == "squirrel")
}//Closes if(Physics.Raycast...)
if(Input.GetMouseButtonUp(0) && wasClicked)
{
drag = false;
var dir = startPos - pos; //calculate direction and intensity
moveDirection = dir * launchForce; //launches with force input
Debug.Log(dir);
isLoaded = false; //frees squirrel from launch zone clamps
isLaunching = true; //allows squirrel to pass through the
//launchPoint triggerzone without being stopped
squirrelActive = true;//allows squirrel to begin moving freely
squirrelDirection = true; //tells squirrel to start moving right
//since they are always moving left
//after returning to the launch tree
wasClicked = false;
}
//Clamps squirrel to specified radius around launchPoint
var movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
var newPos = transform.position + movement;
var offset = newPos - centerPt;
transform.position = centerPt + Vector3.ClampMagnitude(offset,radius);
}// Closes function Update
Thanks for any help!