I have a 2d game with a slingshot firing system, similar to Angry Birds, where I drag the projectile back with the mouse and release to fire. I’ve got code to attempt to prevent the projectile from being dragged all over the screen and should keep it within the “drawrange” of “other” on the closest point toward the mouse. Note that “other” is my projectile’s starting point and “drawrange” is the maximum range I would like the projectile drawn.
if(clicked){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)){
mousePosX = hit.point.x; //world X coord that the hit took place at
mousePosY = hit.point.y; //world Z coord that the hit took place at
if(Vector3.Distance(other.position, transform.position) < drawrange){
transform.position = Vector3(mousePosX, mousePosY, 0);
}else{
dist = Vector3.Distance(other.position, transform.position);
var holderX = dist/drawrange*(other.transform.position.x - mousePosX) + other.transform.position.x;
var holderY = Mathf.Sqrt((drawrange * drawrange) + ((other.transform.position.x-holderX)*(other.transform.position.x-holderX)));
Debug.Log("position =" + holderX + ", " + holderY);
transform.position = Vector3(holderX, holderY, 0);
}
}
}
The issue I’m having is a significant amount of flickering of the projectile as well as motion that is not consistent with where my mouse cursor is. The debug log has a consistent number, but maybe the math routine is taking too long to complete?
I’ve double checked this for math errors but can’t find any. Admittedly my geometry is rusty though. I’m going to attempt to explain my math just in case someone is trying to follow my logic here and it doesn’t make sense.
MATH STUFF:
See attachement