- Home /
Unity prediction line renderer
I am making a 2D game in Unity where I have to throw something. To let the player know where he is throwing at I am trying to show a prediction line renderer on the screen so the player can see where the ball is going to end. The code is partly working. It shows the line, but it is not really. Is it possible to make it 100% accurate?
You can find my code below. The on mouseUp ads the force to my object that I throw while the dragging function "measures" how mutch forse should be added. The DisplayTrajectoryLineRenderer2 renders the line but not accurate enough. Can somebody help me with this problem?
void OnMouseUp () {
ball.isKinematic = false;
ball.AddForce (currentForce * forceMultiplier);
ball.AddTorque (Random.Range(-torqueMultiplier,torqueMultiplier));
timer = timerSlider.value;
clickedOn = false;
thrown = true;
}
void Dragging () {
mouseWorldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
catapultToMouse = mouseWorldPoint - catapult.position;
if (catapultToMouse.sqrMagnitude > maxStretchSqr) {
rayToMouse.direction = catapultToMouse;
mouseWorldPoint = rayToMouse.GetPoint (maxStretch);
}
mouseWorldPoint.z = 0f;
transform.position = mouseWorldPoint;
Debug.DrawLine (catapult.position, mouseWorldPoint, Color.red);
currentForce = catapult.position - mouseWorldPoint;
}
void DisplayTrajectoryLineRenderer2()
{
SetTrajectoryLineRenderesActive(true);
int segmentCount = 20;
float segmentScale = 2;
Vector3 maxPosition = (catapult.position-mouseWorldPoint).normalized * 1.5f + catapult.transform.position;
Vector3 testForce = currentForce * forceMultiplier;
float test = Vector3.Distance (catapult.transform.position, mouseWorldPoint);
Vector3 v2 = maxPosition - mouseWorldPoint;
Vector2[] segments = new Vector2[segmentCount];
segments[1] = mouseWorldPoint;
Vector2 segVelocity = new Vector2(v2.x, v2.y) * torqueMultiplier * test;
//Vector2 testVel = currentForce * forceMultiplier;
for (int i = 1; i < segmentCount; i++) {
// Time it takes to traverse one segment of length segScale (careful if velocity is zero)
float time2 = i * Time.fixedDeltaTime * 5;
// Add velocity from gravity for this segment's timestep
segments[i] = segments[0] + segVelocity * time2 + 0.5f * Physics2D.gravity * Mathf.Pow(time2, 2);
}
TrajectoryLineRenderer.SetVertexCount(segmentCount);
for (int i = 0; i < segmentCount; i++)
TrajectoryLineRenderer.SetPosition(i, segments[i]);
}
Your answer
Follow this Question
Related Questions
How to refract a linerenderer through a 2d object using Physics2D ? 0 Answers
How can I make sure triggers or collisions are never skipped even for high speeds? 2 Answers
Simple 2D Character Movement does not work properly 1 Answer
BoxCollider2D have an offset on collision,Collider2D has an collision offset? 0 Answers