How would you find the angle two parts hit each other?
Asked by
5 years ago Edited 5 years ago
I want to apply a velocity based on where a player touches another player or part.
Let's say I touch PlayerB and I am facing left <--- on a 2D plane. I want to apply a velocity to the left with the X-axis. Vice versa on the right.
However, I also want to be able to apply a downward or upward velocity if I touch the player or the part from above (straight down) or upwards when the hand touches the part/player via animation on all situations.
Current code is
1 | local function getAngle(vectorA, vectorB) |
2 | return math.acos(vectorA.Unit:Dot(vectorB.Unit)) |
5 | local vectorA = player.Character [ part ] .CFrame.lookVector |
6 | local vectorB = otherPart.CFrame.lookVector |
7 | local angle = getAngle(Vector 2. new(vectorA.X, vectorA.Y), Vector 2. new(vectorB.X, vectorB.Y)) |
The angle is always positive. When I get the x and y components, they're also always positive.
1 | local verticalAngle = math.deg(math.sin(angle)) |
2 | local verticalVelocity = initialVelocity * verticalAngle |
The initialVelocity will always be positive as it's just a calculation of how much velocity is needed. The angle should determine whether it's upwards or downwards.
Issue in Studio:
When touching in a direction, the target part moves to the right (positive direction) at all times. If you hit in the right, the y will also go up. However, if you hit in the left, the y will be down while the part continues to go right on the x-axis.
My goal:
A way to ensure that if I touch the part from above (EG animation of touching it from above), the part goes down. If I touch it on my left, the part goes left and maybe up if I touch it at that angle or down if I touch it to the left but downwards. Etc.