Questions in topic: "maths"
http://answers.unity.com/questions/topics/single/2913.html
The latest questions for the topic "maths"Issues constraining angles in CCD
http://answers.unity.com/questions/1639867/issues-constraining-angles-in-ccd.html
I'm terrible at maths and have been working on an IK solution to try and get more comfortable with using maths/angles in Unity.<br>
<br>
I've been able to made a CCD solution which works like this: https://www.youtube.com/watch?v=tZvdZGUxbbc
But when I try to put angle constraints on the joints, I get some weird behaviour - shown here: https://www.youtube.com/watch?v=iYh80XrmDJs&feature=youtu.be<br>
<br>
When constrained there seems to be a dead zone around the hips where the limb fails to reach to target properly and even appears to move away from it.
Here is the code to calculate each joint rotation in the chain:<br>
Vector3 vectorCurrJointToEndEffector = (joints[joints.Length - 1].transform.position - joints[i].transform.position).normalized; //normalised vector from current joint to end effector position
Vector3 vectorCurrJointToTarget = (target.transform.position - joints[i].transform.position).normalized; //normalised vector from current joint to targetposition
float cosineAngle = Mathf.Clamp(Vector3.Dot(vectorCurrJointToEndEffector, vectorCurrJointToTarget), -1.0f, 1.0f); //dot product gives the cosine of the angle for the corrective rotation
//clamping to value between -1 and 1 removes any floating errors
Vector3 crossProduct = Vector3.Cross(vectorCurrJointToEndEffector, vectorCurrJointToTarget).normalized; //normalised cross product gives the axis on which to rotate the joint
float toRotateDegrees = Mathf.Acos(cosineAngle); //calculate joint rotation, in radians
toRotateDegrees = toRotateDegrees * Mathf.Rad2Deg; //get rotation in degrees
joints[i].transform.rotation = Quaternion.AngleAxis(toRotateDegrees, crossProduct) * joints[i].transform.rotation; //apply joint rotation
Here is the code to constrain the joint angles:<br>
Vector3 currentJointEulerAngles = joints[i].joint.transform.localRotation.eulerAngles; //get rotation
//ensure rotation angles stay relative regardless of rotation extent
//X
if (currentJointEulerAngles.x > 180f)
{
currentJointEulerAngles.x -= 360f;
}
currentJointEulerAngles.x = Mathf.Clamp(currentJointEulerAngles.x, joints[i].XaxisMin, joints[i].XaxisMax); //clamp x
//Y
if (currentJointEulerAngles.y > 180f)
{
currentJointEulerAngles.y -= 360f;
}
currentJointEulerAngles.y = Mathf.Clamp(currentJointEulerAngles.y, joints[i].YaxisMin, joints[i].YaxisMax); //clamp y
//Z
if (currentJointEulerAngles.z > 180f)
{
currentJointEulerAngles.z -= 360f;
}
currentJointEulerAngles.z = Mathf.Clamp(currentJointEulerAngles.z, joints[i].ZaxisMin, joints[i].ZaxisMax); //clamp z
joints[i].joint.transform.localEulerAngles = currentJointEulerAngles; //set clamped rotation
Can anyone suggest/provide a fix for this?<br>
<br>
Any help is appreciated. I have been stuck at this stage for over a week now!<br>
Thanksmathconstraintsinverse kinematicmathsTue, 11 Jun 2019 22:30:08 GMTU3DPHow do I round a number to the nearest .25 or .75 number?
http://answers.unity.com/questions/1623834/how-do-i-round-a-number-to-the-nearest-25-or-75-nu.html
Okay, so I know how to round a number to the nearest 0.5 by multiplying it by 2, rounding it, then dividing by 2 again.
I've figured out that doing the same my 4, instead of 2, gives me the nearest .25.
What I need, though, is to round it to the nearest .5, but at an offset of .25.
So, instead of all numbers ending in .0 or .5, they should all end in .25 or .75
I can't figure out the maths for this.
I know I can just add .25 to push it up, but that's not quite what I need.mathsFri, 19 Apr 2019 12:53:34 GMTEstragonHelmerUnit vector (rot) between parent and child
http://answers.unity.com/questions/1623064/unit-vector-rot-between-parent-and-child.html
Hello, I'm trying to get a unit vector representation of the rotation between a child and its parent (using the parent's +Z as reference axis).
The way I'm currently doing it is: childTransform.localRotation * parentTransform.forward;
Is this the correct way? Also, how can I reverse-engineer this so that, given a parent, a child and a unit vector, can I get the angles this unit vector represents?
Thank you very much! :)rotationtransformvectorsmathsThu, 18 Apr 2019 08:10:39 GMTAghawaHelp with orbit path predictor
http://answers.unity.com/questions/1609349/help-with-orbit-path-predictor.html
I basically want to be able to predict the orbit path which I'm currently finding quite difficult due to all the confusing maths and science equations.
I in a sense want to be able to move an orbiting object in a scene and have the orbit prediction path update and show within the scene. This would allow people to make changes to the initial velocity and masses of the objects and see the changed orbital path.
![gravity vector function][1]
This is my current equation for actually making an object orbit around a target object which i just add the returned value to an AddForce() on the orbiting object's rigid body. This I realized doesn't exactly create a completely perfect orbit, though is quite close.
If someone knows how I could create a funtion that gets the all the positions of the orbiting object each cycle to then be rendered on screen, I'd highly appreciate it.
[1]: /storage/temp/134242-1.pngphysicsorbitmathsTue, 05 Mar 2019 23:42:53 GMTPhysicsIsHardRaycasting to get an exact point on an object.
http://answers.unity.com/questions/1601593/raycasting-to-get-an-exact-point-on-an-object.html
Hey guys!
So I got a question about how to find a point on an object using raycasting. Now I know how to raycast to something and get the hit data but my problem is that I'm trying to get exactly where it hit in terms of the objects dimensions as I want to do certain actions depending on where on the cube the raycast hits.
RaycastHit.point returns the point in world space which isnt what im looking for. So far I tried subtracting hit.point from the objects position but since the objects origin isnt in a corner it doesn't return an accurate representation of where on the cube I hit. I drew a picture to explain what I want to get more.
![alt text][1]
[1]: /storage/temp/133099-image.png
(3, 5) being the point I wish to try and get from the raycast.raycastprogrammingpointmathsThu, 14 Feb 2019 00:31:07 GMTAxelizeHow to flip one axis of a quaternion?
http://answers.unity.com/questions/1592182/how-to-flip-one-axis-of-a-quaternion.html
I can successfully read in values from an external IMU and I'm trying to visualize its orientation in Unity, but after I offset it one axis appears to be flipped and I don't know how to reverse it.
I'm reading the orientation in quaternion and I'm trying to avoid using Euler Angles (because of the gimbal lock). Is there a way to flip one axis of a quaternion using only its values (x, y, z, w)?c#quaternionmathsSun, 20 Jan 2019 16:55:29 GMTLeventeXXLMake GameObject rotate forward relative to other gameobject
http://answers.unity.com/questions/1583814/make-gameobject-forward-in-term-of-direction-to-ot.html
I want Enemy rotate straight to Player. So, A Enemy Fire to Player![alt text][1]
[1]: /storage/temp/129985-photo-2018-12-25-11-14-57.jpgmathsTue, 25 Dec 2018 05:47:05 GMT$$anonymous$$How to Work Out Time Passed in Seconds (Using System.DateTime.Now)?
http://answers.unity.com/questions/1580256/how-to-work-out-time-passed-in-seconds-using-syste.html
Hi, this is more a maths related question, rather than a programming one, but code is greatly appreciated.
I have a float value, of 86400, which I'll call Time - the total amount of seconds in a day. I need to use System.DateTime.Now.Hour, Minute, Second and convert them into a float value that fits within Time.
I've read online that you can just do 24*60*60, but that's not giving me the correct results, so I'm posting it here.
Thanks in advance!timesystemsecondsdatetimemathsWed, 12 Dec 2018 08:06:12 GMTTSCSimulation_AHFind corners/edges on a shape using own implementation
http://answers.unity.com/questions/1564927/find-cornersedges-on-a-shape-using-own-implementat.html
I'm trying to get the corners of the following shape:
![enter image description here][1]
By corners I mean this (red dots):
![enter image description here][2]
The minimum quantity of points that can define this shape.
And I have implemented the following:
public Shape Optimize()
{
// If the vertices are null or empty this can't be executed
if (vertices.IsNullOrEmpty())
return this; // In this case, return the same instance.
if (!edges.IsNullOrEmpty())
edges = null; //Reset edges, because a recalculation was requested
// The corners available on each iteration
var corners = new Point[] { Point.upperLeft, Point.upperRight, Point.downLeft, Point.downRight };
//The idea is to know if any of the following or previous vertice is inside of the the array from upside, if it is true then we can add it.
Point[] vs = vertices.ToArray();
for (int i = 0; i < vertices.Count - 1; ++i)
{
Point backPos = i > 0 ? vs[i - 1] : vs[vertices.Count - 1],
curPos = vs[i], //Punto actual
nextPos = i < vertices.Count - 1 ? vs[i + 1] : vs[0];
// We get the difference point between the actual point and the back & next point
Point backDiff = backPos - curPos,
nextDiff = nextPos - curPos,
totalDiff = nextPos - backPos;
if (corners.Contains(backDiff) || corners.Contains(nextDiff) || corners.Contains(totalDiff))
AddEdge(curPos, center); // If any of the two points are defined in the corners of the point of before or after it means that the actual vertice is a edge/corner
}
return this;
}
This works rectangled shapes, but rotated shapes are very sharp, so, this code doesn't work well:
![enter image description here][3]
* Blue pixels (in this photo and the following) are the `vertices` variable processed on `Optimize` method.
* Green pixels are the detected corners/edges (on both photos).
But sharpness in a shape only defines the side inclination, so what can I do to improve this?
Also, I have tested [Accord.NET BaseCornersDetector inherited classes][4], but the best result is obtained with [HarrisCornersDetector][5], but:
![enter image description here][6]
Many edges/corners are innecesary, and they aren't in the needed place (see first photo).
[1]: https://i.stack.imgur.com/N68XN.png
[2]: https://i.stack.imgur.com/aehKI.png
[3]: https://i.stack.imgur.com/LTwO1.png
[4]: http://accord-framework.net/docs/html/T_Accord_Imaging_BaseCornersDetector.htm
[5]: http://accord-framework.net/docs/html/T_Accord_Imaging_HarrisCornersDetector.htm
[6]: https://i.stack.imgur.com/mqCKu.pngtexture2dshapemathsedgesMon, 22 Oct 2018 21:32:28 GMTz3nth10nhow to check if a number is between one range
http://answers.unity.com/questions/1561247/how-to-check-if-a-number-is-between-one-range.html
hello!
i know that it's a stupid question, but i have to check continuosly if a number is between one range (negative number included) maybe is a elementary school question about math...
for example 0 < p < 1 or -1 < p< 1
thank's you in andvancemathmathsTue, 09 Oct 2018 23:58:08 GMTSylon87Finding RayCastHit's Origin Position
http://answers.unity.com/questions/1554687/finding-raycasthits-origin-position.html
I'm using Rigidbody.SweepTest to let my AI know when to jump. Problem is, when going uphill it won't stop jumping because the ray it makes will hit the ground next to it no matter what distance I put in because what it does is making rays from every point in my AI's body (so if it's the lowest point it will always hit the ground when going uphill). I only want my AI to jump when going uphill when the slope is 45 and bigger (including 90 of course). So what I did is using the RayCastHit I got from the Rigidbody.SweepTest to do that:
MyRigidbody.SweepTest(transform.forward, out hit, float.MaxValue);
if(Vector3.Distance(transform.position, ORIGIN) / hit.distance >= 1)
// Jump
Problem is that I don't know how to get the origin point of the ray (it's always different it goes out from different points of my AI's body). Also if there's anything wrong with my other code please let me know I'm basically finding the slope by dividing the distance from my AI's lowest point (transform.position) to the ray origin by the distance from the ray origin to the ray hit point.raycastairaycastingmathsraysWed, 19 Sep 2018 11:01:29 GMTSoogbadHow do box collider collisions work mathematically?
http://answers.unity.com/questions/1547532/how-do-box-collider-collisions-work-mathematically.html
Hi
I want to know how the Box Collider works in Unity. I have read all of the Unity documentation and PhysX documentation but there are not any detailed explanations as to exactly how they work (possibly because it's confidential IP).
How does a box collider know when it is intersecting/overlapping another box collider?
What metric is actually measured to know when a collision has taken place? Does it look to see if there is a point or vertex in the box collider is inside the volume of another collider? If so how does it know that a vertex is within the volume of another collider?
What are box colliders made from? Is it lots of small objects put together or is it one big object?
Thanks for your help in advancecolliderdetectionbox colliderphysxmathsWed, 29 Aug 2018 10:04:42 GMTunity_cma7iR9olN89VAHow can I get a point position in circle line
http://answers.unity.com/questions/1545128/how-can-i-get-a-point-position-in-circle-line.html
![alt text][1]
[1]: /storage/temp/123196-untitled-1-recovered.png
Positions on the three-dimensional plane are 45 degrees apart on the circle. The positions corresponding to the angles are indicated on the left. What happens to the position of a random angle coming from the central point of the circle in the 3-dimensional plane on the corresponding circle line? As an example, I try to find the position between two specific positions of a random angle that emerges from the 45 degree circular section of the circle I have specified in blue.mathmathsmathf.sinmathf.cosWed, 22 Aug 2018 17:42:49 GMTmryasaremirConvert rigidbody.drag to acceleration(m/s²)?
http://answers.unity.com/questions/1528433/convert-rigidbodydrag-to-accelerationms.html
Drag afaik is kinda modifying velocity every FixedUpdate like:
velocity *= 1-Mathf.Clamp01(drag*Time.fixedDeltaTime);
or maybe
velocity -= velocity*Mathf.Clamp01(drag*Time.fixedDeltaTime);
or something like that (found on forums).
Is the conversion even possible? I'm pretty sure that 0 drag = 0 deceleration and 1/Time.fixedDeltaTime drag = infinite deceleration (which makes it dependent on fixedDeltaTime, tested, looks like a bug). So I ended with constructions like:
dragFactor = 1-Mathf.Clamp01(drag*Time.fixedDeltaTime);
deceleration = 1/dragFactor; //can't be <1, wrong proportions
or even
deceleration = 1/Mathf.Pow(dragFactor,1/dragFactor); //can't be <1 too, relatively right proportions
What I'm doing is replacing rigidbody bullets with raycasts based on their parameters. What I'm trying to find is stopping distance (S = v0^2 * 2*a) and speed after some distance traveled (v = v0^2 - 2aS). This strange formula that I found by scratching my head and randomly swapping numbers and operands for like two days is kind of worked:
float StopDist(float speed, float drag) {
float dragFactor = 1-Mathf.Clamp01(drag*Time.fixedDeltaTime);
return speed * Mathf.Pow(dragFactor,1/dragFactor);
}
but failed on high drag / low distances. And this is like for speed after traverse:
float CurrSpeed(float initSpeed, float drag, float dist) {
float dragFactor = 1-Mathf.Clamp01(drag*Time.fixedDeltaTime);
float deceleration = 1/Mathf.Pow(dragFactor,1/dragFactor)-1; //-1 is temporal workaround
return initSpeed-Mathf.Max(0,dist*deceleration);
}
I'm only need these two formulas (even based on drag), but conversion is much much better.physicsdragaccelerationmathsThu, 12 Jul 2018 11:54:40 GMTServailCalculating the Hit Point on a Sphere (with Rotation, Based on Static Nodes)
http://answers.unity.com/questions/1511943/calculating-the-hit-point-on-a-sphere-with-rotatio.html
Hi,
I am currently working on procedurally generating spheres at runtime using a subdivided icosahedron.
So far, I have managed to create an icosahedron and subdivide this a specified number of times. I am then mapping the vertices of the subdivided shape as the center points of the hexagons (and 12 pentagons) that are being created, and generating the hexagons from the center points of all adjacent triangles.
These "nodes" (the hexagon center points) are generated at game launch and are static; they never move. When clicking on the surface of the sphere, I loop through all these nodes and find the nearest one to the mouse click and create a simple cube at the center of the hexagon.
This works great when the sphere has a rotation of [0, 0, 0]. Even when the camera is rotated around the sphere at weird angles, the logic holds up for clicking on the surface of the sphere. However, when the sphere itself starts to rotate, the logic breaks down.
I know exactly why this is the case; I am mapping to the position of the nodes (which are static). With the sphere rotating, the nodes no longer map to their visual counterparts (the hexagons) and, as such, the placement logic does not work.
I understand the basic premise for calculating the correct visual placement:
1. Take the click point on the sphere and rotate the point opposite to the sphere's rotation. This will map my click point back to the original node positions.
2. Calculate the closest node using the existing logic now that the point is in "node" space.
3. With the closest node found, map the node's position back to the sphere's rotation so that the cube is placed at the center of the correct hexagon visually.
I have been trying to work this out for a few days but I cannot find how to do this. I believe the main issue relies in rotating my click position in "world" space to "node" space and, then, vice versa when the nearest node has been found.
Is anybody able to help in calculating the mathematical function that is required to convert my point from "world" to "node".
I have looked into Quaternion.Inverse to 'reverse' the sphere's rotation and used the following function to rotate a point around a point (the origin):
private Vector3 RotateAroundPoint( Vector3 point, Vector3 pivot, Quaternion rotation )
{
return rotation * ( point - pivot ) + pivot;
}
but neither of these methods seem to be working for what I want. The cubes sometimes even place themselves way away from the surface of the sphere, which is definitely wrong!!
Any help would be greatly appreciated as I cannot solve this by myself :)c#rotationspherelogicmathsTue, 29 May 2018 11:47:03 GMTImmersiveWorksFinding the Correct Node on a Rotated Sphere
http://answers.unity.com/questions/1511940/finding-the-correct-node-on-a-rotated-sphere.html
Hi,
I am currently working on procedurally generating spheres at runtime using a subdivided icosahedron.
So far, I have managed to create an icosahedron and subdivide this a specified number of times. I am then mapping the vertices of the subdivided shape as the center points of the hexagons (and 12 pentagons) that are being created, and generating the hexagons from the center points of all adjacent triangles.
These "nodes" (the hexagon center points) are generated at game launch and are static; they never move. When clicking on the surface of the sphere, I loop through all these nodes and find the nearest one to the mouse click and create a simple cube at the center of the hexagon.
This works great when the sphere has a rotation of [0, 0, 0]. Even when the camera is rotated around the sphere at weird angles, the logic holds up for clicking on the surface of the sphere. However, when the sphere itself starts to rotate, the logic breaks down.
I know exactly why this is the case; I am mapping to the position of the nodes (which are static). With the sphere rotating, the nodes no longer map to their visual counterparts (the hexagons) and, as such, the placement logic does not work.
I understand the basic premise for calculating the correct visual placement:
1. Take the click point on the sphere and rotate the point opposite to the sphere's rotation. This will map my click point back to the original node positions.
2. Calculate the closest node using the existing logic now that the point is in "node" space.
3. With the closest node found, map the node's position back to the sphere's rotation so that the cube is placed at the center of the correct hexagon visually.
I have been trying to work this out for a few days but I cannot find how to do this. I believe the main issue relies in rotating my click position in "world" space to "node" space and, then, vice versa when the nearest node has been found.
Is anybody able to help in calculating the mathematical function that is required to convert my point from "world" to "node".
I have looked into Quaternion.Inverse to 'reverse' the sphere's rotation and used the following function to rotate a point around a point (the origin):
private Vector3 RotateAroundPoint( Vector3 point, Vector3 pivot, Quaternion rotation )
{
return rotation * ( point - pivot ) + pivot;
}
but neither of these methods seem to be working for what I want. The cubes sometimes even place themselves way away from the surface of the sphere, which is definitely wrong!!
Any help would be greatly appreciated as I cannot solve this by myself :)c#spherelogicmathsTue, 29 May 2018 11:41:30 GMTImmersiveWorksInversing fixed delta time
http://answers.unity.com/questions/1510566/inversing-fixed-delta-time.html
void Awake()
{
initialFixedTime = Time.fixedDeltaTime;
}
void FixedUpdate()
{
Time.fixedDeltaTime = Time.timeScale * initialFixedTime;
fixedTimeFactor = 0.01f / initialFixedTime;
inverseFixedTimeFactor = 1 / fixedTimeFactor;
camForward = Vector3.Lerp(camForward, targetForward, 0.05f * inverseFixedTimeFactor);
}
This whole block of code is confusing.
1. What is the point of setting `Time.fixedDeltaTime` ?
2. What is the advantage over using `Time.deltaTime`?
3. What is happening with all those factors?
4. Testing it, it does give a smooth interpolation, but what is really happening here?cameralerpfixedupdatedeltatimemathsFri, 25 May 2018 12:41:21 GMTvalis0000Help with Fuel burn/Acceleration ratio equation
http://answers.unity.com/questions/1498305/help-with-fuel-burnacceleration-ratio-equation.html
I need help to figure out the equation for my ship's fuel burn ratio....
I am not measuring the ships speed, but instead its acceleration. In fact the user doesn't not even enter a speed, they simply enter the desired travel time and it gets measured in a ratio from 0 to 1 (start to finish). I then have a conversion to game units - which when all said and done gives me a pseudo Metres p/s measurement. For example, *Travel from Here to there in 3 days will required 0.5G's*
Also, the ship does a flip at 0.5 of the journey and applies the same acceleration rate in the opposite direction to bring it to a stop by 1.0 (basic space travel principal)
So now I want to implement a fuel system and have the ship burn fuel at 100% efficiency at a particular rate, but get less efficient as it accelerates faster and then become more efficient at really slow accelerations.
Here are my *knowns* :
**Travel Time (t)** (entered by the user in days)
**Destination (d)** (entered by user, can get vector3 from this)
**Acceleration** (not directly entered by user, but determined from (t) and (d)
**Fuel (f)** (not implemented yet, but would like to have user enter an **int** not a float *(as in, user has 100 fuel pellets, but each fuel pellet provides x amount acceleration for certain number of days)*
**100% efficiency rate (e)** (The number of G's at which the ship is using 1 pellet per 1 day whilst accelerating)
Anyway, a lot of the existing maths I have was done by a colleague, not me, so this might be simple, but I was too busy drawing cartoons in high school maths class, so I need help.
Thank youc#accelerationmathsWed, 25 Apr 2018 00:10:15 GMTTonkoTesting player distance is not consistent
http://answers.unity.com/questions/1464400/testing-player-distance-is-not-consistent.html
I am trying to get an enemy to follow the player when they are within a certain distance of the player. If the player gets far enough away the enemy will go back to looking for food. However my current script seems to be throwing out some weird results. Sometimes when the player is within the range it will instead decide it is not and go after the food, and about half the time when the player is outside of the range it will decide to go after the player anyway with the weird result that it will bounce back and forward undecided between player and food source.
Here is the code for determining if the player is in range, called every second.
void lookForPlayer()
{
Vector3 playerLocation = GameObject.Find("Player").transform.position;
Vector3 curentPosition = transform.position;
float playerDistance = Vector3.Distance (playerLocation, curentPosition);
if (playerDistance <= playerSearchDistance)
{
canSeePlayer = true;
print ("I can see you");
}
if (playerDistance > playerSearchDistance)
{
canSeePlayer = false;
print ("I'm hungry now.");
}
}
I have quintuple checked. The only other times the variable "canSeePlayer" appear in the code are when it is declared and the two times I check it each update to determine if it is true (face player) or false (face the food). Both of these are definitely using == to check and not =.
Is there some error in how I am arriving at the distance that would throw out this randomisation of results?errordistance checkmathsMon, 05 Feb 2018 11:36:37 GMTNEOperaHow to make a ship simulation system based on mathematical formulas
http://answers.unity.com/questions/1443856/how-to-make-a-ship-simulation-system-based-on-math.html
Hello everyone, I would like guidance on how to make a ship simulator based on mathematical formulas I have from a research paper. It has formulas for sea, weather and ship model behaviour as well.
Thanks in advance.physicsmodelshipmathsMon, 18 Dec 2017 00:35:30 GMThellenicshipsWhy is my transform.rotatearound reset only working on positive Y?
http://answers.unity.com/questions/1437832/why-is-my-transformrotatearound-reset-only-working-1.html
Hey there,
<hr>
So I wanted to make a reset for my transform.rotatearound so that if someone moves the player, it will go back to a standstill. It was all well and good until I wanted to make it smooth rather than sudden. This is not necessary but is desired to make my game a little less... rough.
<hr>
To make it smooth, rather than subtracting the Y-Rotation from the reset object rotation, I wanted to subtract 10% of the Y-Rotation from the reset object rotation. My logic is, for example 0 - (30 / 10) = -3 and that 0 - (-30 / 10) = 3 {Dus, adding on 30 to the -30 of the Y.)
<hr>
Hopefully, that makes sense. To me, my logic makes sense and it should work for left and right. However, in reality, it only works when I am subtracting from a positive Y. The code is below, hopefully, someone can help shed light on my situation.
<hr>
Thank you for your help in advanced - 1sd15.
<hr>
using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour {
public float mouseSensitivity;
public GameObject gameShip;
public GameObject resetObject;
void Update ()
{
if (Input.GetAxis("Mouse X") < 0)
{
transform.RotateAround(gameShip.transform.position, Vector3.up, Time.deltaTime * mouseSensitivity);
}
if(Input.GetAxis("Mouse X") > 0)
{
transform.RotateAround(gameShip.transform.position, Vector3.down, Time.deltaTime * mouseSensitivity);
}
if (Input.GetKey("up"))
{
transform.RotateAround(gameShip.transform.position, Vector3.up, resetObject.transform.eulerAngles.y - (gameObject.transform.eulerAngles.y / 10));
}
}
}c#unity 5rotationeuleranglesmathsSat, 02 Dec 2017 08:48:59 GMT1sd15I have no idea why this isnt working
http://answers.unity.com/questions/1431290/i-have-no-idea-why-this-isnt-working-1.html
i have made a script to try to find Pi, but the text component i have referenced just says 4, btw i am using this method "Leibniz formula for π" - https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
Here is my code :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PaddleShape : MonoBehaviour {
private bool isNextNegative = false;
private int lastFraction = 1;
private decimal currentTotalOfFractions;
private Text text;
void Start()
{
text = GetComponent<Text>();
Invoke("Golden", 1.5f);
}
void Golden()
{
decimal fractionValue = 1 / lastFraction;
if (isNextNegative)
fractionValue = -fractionValue;
currentTotalOfFractions += fractionValue;
text.text = (currentTotalOfFractions * 4).ToString();
lastFraction += 2;
isNextNegative = !isNextNegative;
Invoke("Golden", Mathf.Epsilon);
}
}invokecalculatemathsFri, 10 Nov 2017 17:51:05 GMTfinlay_morrisonComputing Particle System Center of Mass
http://answers.unity.com/questions/1366948/comuting-particle-system-center-of-mass.html
Well, I have a system where particles have gravity and can collide with the terrain, and that means particles can move away from their start position, and obiously it's center of mass will not be the original position of PS GameObject, well that's my questionparticle systemmathscenterofmassSun, 18 Jun 2017 02:33:44 GMTJotaRataHow do I convert a number and a range to another directly proportional number and range?
http://answers.unity.com/questions/1360380/how-do-i-convert-a-number-and-a-range-to-another-d.html
This question is really hard to formulate.
Let's say I have a range of 0 - 100, and the number 56.
I want to convert the number 56 to be directly proportional to the range of (0 - 3) and convert it in tsaid range.
Example: Number 50, range is (0 - 100)
Output number is 1.5 in the range (0 - 3), directly proportional to what is abovec#mathmathfrangemathsWed, 31 May 2017 19:57:32 GMTtommyzatMultiple Lerp Calculations
http://answers.unity.com/questions/1328867/multiple-lerp-calculations.html
A project I'm involving myself in will involve a single object with multiple parts (a gun) being animated through multiple in-code lerps. Doing this because it seems more efficient when I need the to do stuff like moving the gun whilst the slide's pulled back and such.
What's an efficient and slightly less confusing way of containing all of the code required to do lerp animations without the endless blocks upon blocks of maths code?lerpmathsMon, 20 Mar 2017 19:24:52 GMTSourTarteNeed help for direction calculation.
http://answers.unity.com/questions/1324028/need-for-for-direction-calculation.html
Hi
I need help regarding a question related to maths/vector.
Attached scripts contain the flocking algorithm. All the flocks follow the target/goal (as shown in the below image). Everything is working fine when the placement of the manager script is at position 0,0,0 x,y,z coordinates. But I don’t them to be placed at vector3.zero.
So, I want the help for editing the script. I want as I can place the manager at anywhere in the World and result should be same.
Following is the reference from where I got the source code/tutorial:
https://www.youtube.com/watch?v=eMpI1eCsIyM
Source files: http://files.holistic3d.com/yt/eMpI1eCsIyM.zip
Pastebin code for the same scripts:
flock.cs: http://pastebin.com/2nAWvdK8
globalFlock.cs: http://pastebin.com/LMUzfEdM
I just edited the source files just to make all the fishes child of the parent:
https://www.dropbox.com/s/9xo3olv0x8dxfj4/FishesUpdated.unitypackage?dl=0
P.S. I think the issue is in the flock.cs there is a line just after the if(turning)
which is calculating the direction:
Vector3 direction = Vector3.zero - transform.position;
Please help me out.
Thanks,
Harshdeepvector3directionmathsFri, 10 Mar 2017 08:10:23 GMTitsharshdeepsmooth rotate around x-axis using quaternion.slerp
http://answers.unity.com/questions/1303378/smooth-rotate-around-x-axis-using-quaternionslerp.html
hi all,
i want to rotate sphere around x-axis by the amount of displacement made by via dragging mouse in vertical direction on screen.
how to calculate the angle as per dragging distance by which sphere is supposed to rotate around x-axis.
Please helpunity 5mathsquaternion.slerpTue, 24 Jan 2017 12:26:59 GMTchetan-raneApplying a script to two objects not working
http://answers.unity.com/questions/1270352/applying-a-script-to-two-objects-not-working.html
In short, I've got these blocks which, when collided with, generate a random + or - problem e.g 2 - 5. Now I originally only had one of these blocks in the first level but other levels will need more than one. I have been working for hours trying to find a way to allow blockade 1 and 2 to be able to be affected by the script. Once the question is answered correctly, the blockade will be destroyed allowing the player to continue. Here is the code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Collisions : MonoBehaviour
{
public GM gm = new GM();
private int N1;
private int N2;
private int AnswerCorrect;
public Text inputfield;
public Text QuestionBox;
public GameObject QuestionPanel;
string opperand;
public GameObject Blockade;
public GameObject Blockade2;
public GameObject Enemy;
public KeyCode Submit;
void Update()
{
if (Input.GetKey(Submit))
{
CheckAns();
}
}
public void QuestionMaker()
{
string myOperator = GetRandomOperator();
QuestionBox.text = "What is " + N1 + myOperator + N2 + "?";
}
public string GetRandomOperator()
{
int randomOperator = Random.Range(0, 2);
N1 = Random.Range(1, 10);
N2 = Random.Range(1, 10);
switch (randomOperator)
{
case (0):
opperand = "-";
AnswerCorrect = N1 - N2;
break;
case (1):
opperand = "+";
AnswerCorrect = N1 + N2;
break;
}
return opperand;
}
public void CheckAns()
{
if (inputfield.text == AnswerCorrect.ToString())
{
Destroy(Blockade);
QuestionPanel.SetActive(false);
}
else
{
QuestionMaker();
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "End")
{
Scene scene = SceneManager.GetActiveScene();
SceneManager.LoadScene(scene.buildIndex + 1);
}
if (col.gameObject.name == "Blockade")
{
QuestionPanel.SetActive(true);
QuestionMaker();
GetRandomOperator();
CheckAns();
}
if (col.gameObject.name == "Blockade2")
{
QuestionPanel.SetActive(true);
QuestionMaker();
GetRandomOperator();
CheckAns();
}
}
}
I am well aware that this will not work because I removed all the things I tried so that whoever replies may have a crack at it. Thank you.c#2dcollision2ddestroygameobjectmathsSat, 12 Nov 2016 09:42:15 GMTVIGamingFinding angles between Vectors to Work Out If Three of Them are Collinear
http://answers.unity.com/questions/1264305/finding-angles-between-vectors-to-work-out-if-thre.html
So... I'm working on a rope swing prototype and in short, I need to find an angle between some vectors or if I can can draw a straight-line between three different vectors. I've been searching for ages but can't seem to find any clear solution.
Say I have three vectors, Vector1,Vector2 and Vector3, I need to find the angle between Vector1 and Vector3 and Vector1 and Vector2. If they're the same then I unwrap the rope.
The other way to do this, is just if I can draw one straight line through all three Vectors then I unwrap.
I think I might be able to use the equation of a straight line, but I'm not sure how to apply the maths to vector positions.
Hope I was clear enough. C# is preferable.vector3anglesropemathsSat, 29 Oct 2016 21:13:17 GMTDarkwingerBetter Barrel and Turret movement with ballistic targeting + drag [c#]
http://answers.unity.com/questions/1259405/better-barrel-and-turret-movement-with-ballistic-t.html
Hi I'm new to unity, and C# in general. But I've made some decent progress but i'm a long way off from totally understanding everything i'm stitching together from various tutorials (Quaternion calculations and radons etc just completely allude me).
Basically i have tank, the turret need to rotate towards the target on the Y axis, and the gun barrel then needs to elevate to the target + the extra needed for the trajectory. I've actually done this and works fine. [pic0]
My issues:
- Some tanks need to have limited turret rotation &| barrel elevation ( eg tank destroyers vs turreted tanks).
- I have two workings versions of the turret rotation script, the first is commented out. Now the first is actually better, because it locks the turret to the parent axis and prevents tilting or elevating, which is what i actually want - but I just cant seem to incorporate this into a workable autoaim [pic1]. Whereas version two (not commented out works, but is cheating by keeping the turret horizontal to the world at all times [pic0]
- oh and finally, as a bonus i'd love someone to tell me how i can incorporate drag into my ballistic calculator so i'll have a variable i can divide the penetration value to for shots a long range. Ideally i'd like to set "2" to the drag field in the projectiles rigidbody and then incorporate "2" into the ballistic calculator. But i fear this going to require some advance mathematics based on distance, and while i understand (barely) the wiki page on the subject, im not sure how i can combine both calculations into a single formula.
So here's my code:
void Update () {
if (target != null) {
/*
Quaternion qTurret;
Transform trans = turret;
float distanceToPlane = Vector3.Dot(trans.up, target.transform.position - trans.position);
Vector3 planePoint = target.transform.position - trans.up * distanceToPlane;
qTurret = Quaternion.LookRotation(planePoint - trans.position, trans.up);
trans.rotation = Quaternion.RotateTowards(turret.transform.rotation, qTurret, (moveSpeed * 10) * Time.deltaTime);
Vector3 OurPos = this.gameObject.transform.position;
float angle1 = scripts.GetComponent<BallisticCalc> ().CalculateTrajAngles (shellVelocity, OurPos, target.transform);
barrel.transform.localEulerAngles = new Vector3 (angle1, 0, 0);
*/
Vector3 OurPos = this.gameObject.transform.position;
float angle1 = scripts.GetComponent<BallisticCalc> ().CalculateTrajAngles (shellVelocity, OurPos, target.transform);
Vector3 destDir = target.transform.position - turret.position;
destDir.y = 0;
Quaternion targetRotation = Quaternion.LookRotation (destDir);
turret.rotation = Quaternion.RotateTowards (turret.rotation, targetRotation, (moveSpeed * 10) * Time.deltaTime);
barrel.transform.localEulerAngles = new Vector3 (angle1, 0, 0);
}
}
and my ballistic calculator:
public float CalculateTrajAngles(float velocity, Vector3 start, Transform target){
float v = velocity;
Vector3 targetVector = target.position - start;
float height = targetVector.y;
targetVector.y = 0;
float x = targetVector.magnitude;
float y = height;
float g = Mathf.Abs(Physics.gravity.y);
float top = v*v + Mathf.Sqrt(v*v*v*v - (g*(g*x*x + 2*y*v*v)));
float bottom = g*x;
float angle1 = Mathf.Atan2(bottom,top);
return -angle1 * Mathf.Rad2Deg;
}
Any help appreciated.
[pic0][1]
[pic1][2]
[1]: http://www.afdt.co.uk/img/pic0.jpg
[2]: http://www.afdt.co.uk/img/pic1.jpgrotationmathsturretsballisticThu, 20 Oct 2016 08:35:30 GMTfoxdie01