# How do I write ClampMagnitude?

I’m working on a project for my schools finals and I am making a sprite with drag n shoot mechanic. My problem is that it doesn’t really have a limit to how far it can go, so I was trying to find the answer when I found clampmagnitude. now I can see this is helpful but I don’t how how to add it within the code since I am currently learning as I’m making the game. I’ll put the code I have so far but if anyone could help that would be amazing.

``````using UnityEngine;

public class Player : MonoBehaviour
{
public float power = 5f;

Rigidbody2D rb;

LineRenderer lr;

Vector2 DragStartPos;

private void Start() {
rb = GetComponent<Rigidbody2D>();
lr = GetComponent<LineRenderer>();
}

private void Update() {
if (Input.GetMouseButtonDown(0)) {
DragStartPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}

if (Input.GetMouseButton(0)) {
Vector2 DragEndPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 _velocity = (DragEndPos - DragStartPos) * power;

Vector2[] trajectory = Plot(rb, (Vector2)transform.position, _velocity, 500);

lr.positionCount = trajectory.Length;

Vector3[] positions = new Vector3[trajectory.Length];
for (int i = 0; i < trajectory.Length; i++) {
positions _= trajectory*;*_
``````

* }*
* lr.SetPositions(positions);*
* }*

* if (Input.GetMouseButtonUp(0)) {*
* Vector2 DragEndPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);*
Vector2 _velocity = (DragEndPos - DragStartPos) * power;

* rb.velocity = velocity;
_
}*

* if (Input.GetMouseButton(0))*
* {*
* Time.timeScale = 0.3f;*
_ Time.fixedDeltaTime = 0.02f * Time.timeScale;_
* }*

* if (Input.GetMouseButtonUp(0))*
* {*
* Time.timeScale = 1f;*
_ Time.fixedDeltaTime = 0.02f * Time.timeScale;_
* }*

}

public Vector2[] Plot(Rigidbody2D rigidbody, Vector2 pos, Vector2 velocity, int steps) {
* Vector2[] results = new Vector2[steps];*

* float timestep = Time.fixedDeltaTime / Physics2D.velocityIterations;*
_ Vector2 gravityAccel = Physics2D.gravity * rigidbody.gravityScale * timestep _
_
timestep;*_

_ float drag = 1f - timestep * rigidbody.drag;
Vector2 moveStep = velocity * timestep;_

* for (int i = 0; i < steps; i++){*
* moveStep += gravityAccel;*
_ moveStep = drag;_
_
pos += moveStep;_
_ results = pos;
}
return results;
}
}*_

You can insert it here:

``````Vector2 _velocity = Vector2.ClampMagnitude(DragEndPos - DragStartPos * power, 1);
``````

Replace 1 with the maximum velocity you want. You may need to do similar in other parts of your code if you have UI that you also want to limit etc.