Rotate a capsule between two points

Let’s say there are two point A and B. A capsule object need to go from point A to B.
I already did the scaling part but can’t seems to get how the rotation is working.
My code part for rotation is
pointA is (p1x,p1y,p1z)
pointB is (p2x,p2y,p2z)

        float dirx = (p1x + p2x) / 2 - p1x;
        float diry = (p1y + p2y) / 2 - p1y;
        float dirz = (p1z + p2z) / 2 - p1z;

        float len = (float)Math.Sqrt(dirx * dirx + diry * diry + dirz * dirz);
        float x_angle = (float)Math.Acos(dirx / len);
        x_angle= x_angle * 180 / 3.1415f;

        float y_angle = (float)Math.Acos(diry / len);
        y_angle = y_angle * 180 / 3.1415f;

        float z_angle = (float)Math.Acos(dirz / len);
        z_angle = z_angle * 180 / 3.1415f;
        c1.transform.eulerAngles = new Vector3(x_angle-90,y_angle, z_angle-90);

I suggest using included methods like transform.Rotate(Around) or Quaternion.Lerp

1 Like

Dude, read the Unity manual or do a tutorial. Don’t reinvent the wheel. You use an engine so you don’t have to do things like that.

To move stuff you use Translate method, to rotate you use Rotate method. To add some physics to movement you have AddForce.

1 Like

Brother I am doing a project where python script is sending me coordinate by socket programming and I have to put the capsule between 2 points. Rotate method need and angle x y z value. All I am asking how to calculate that. or some other method all ready exist.

Brother I am stuck at how to calculate the angle for rotation.

Explain the issue you have and what you want to do, then I might be able to help

Your first problem’s using Python in Unity, it uses C#!

1 Like

let say 2 point location is given. point a and point b. I need to alligned a cylindrical object or capsule object between 2 point shown in picture.

8753698--1186195--yzplane.PNG

@FatinFardaous first calculate a vector between points A and B, then align your object along that vector. Use existing Unity commands to do that.

Something like this would align an object between 2 points I think:

// Calculate a vector from point A to B
Vector3 vectorAB = pointB.transform.position - pointA.transform.position;
// Calculate the center point
Vector3 center = (pointA.transform.position + pointB.transform.position) / 2f;
// Set position of the object if your pivot is in the center
alignedObject.transform.position = center;
// Adjust up vector to rotate the object
alignedObject.transform.up = vectorAB;

8753941--1186231--20230124_align_between_2_points.PNG

There are many different ways to do this, I think you could use LookAt, or calculate an angle from the AB vector, and then use Quaternion.Euler to set the rotation if you just need to do a rotation on one plane. But this pseudo code I showed should work for 3D.

3 Likes

Well done, I might have a go at that meself at some point :smile:

1 Like

Thanks for the help.:slight_smile: