Questions in topic: "maths"
http://answers.unity.com/questions/topics/single/2913.html
The latest questions for the topic "maths"How can we roll the box not cube also need to work with physics
http://answers.unity.com/questions/1813752/how-can-we-roll-the-box-not-cube-also-need-to-work.html
Hi Guys, I need to roll the box (not the cube), the size of the box will be like this x=1, y=2, z=1
How can we achieve this? Also I need to fall down the box if not exits floor,
Please watch this video.
[https://youtu.be/C_6m1uVw49g][1]
public class cubePlayer : MonoBehaviour
{
public bool isRolling;
public float rotateSpeed;
private Bounds bound;
private Vector3 left, right, up, down;
// Start is called before the first frame update
void Start()
{
bound = GetComponent<BoxCollider>().bounds;
left = new Vector3(-bound.size.x / 2, -bound.size.y / 4, 0);
right = new Vector3(bound.size.x / 2, -bound.size.y / 4, 0);
up = new Vector3(0, -bound.size.y / 4, bound.size.z / 2);
down = new Vector3(0, -bound.size.y / 4, -bound.size.z / 2);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A) && !isRolling)
{
StartCoroutine(Roll(left));
}
else if (Input.GetKey(KeyCode.D) && !isRolling)
{
StartCoroutine(Roll(right));
}
else if (Input.GetKey(KeyCode.W) && !isRolling)
{
StartCoroutine(Roll(up));
}
else if (Input.GetKey(KeyCode.S) && !isRolling)
{
StartCoroutine(Roll(down));
}
}
IEnumerator Roll(Vector3 positionToRotation)
{
isRolling = true;
Debug.Log(positionToRotation);
float angle = 0f;
Vector3 point = transform.position + positionToRotation;
Vector3 axis = Vector3.Cross(Vector3.up, positionToRotation).normalized;
while (angle < 90f)
{
float angleSpeed = Time.deltaTime + rotateSpeed;
transform.RotateAround(point, axis, angleSpeed);
angle += angleSpeed;
yield return null;
}
transform.RotateAround(point, axis, 90 - angle);
isRolling = false;
}
}
[1]: https://youtu.be/C_6m1uVw49gunity 5physicsmathsFri, 12 Feb 2021 08:39:32 GMTvishnujayaraj128Trying to clamp a second position to 45 degrees in 2d space
http://answers.unity.com/questions/1802195/trying-to-clamp-a-second-position-to-45-degrees-in.html
I have a vector2 origin position. I have a secondary position, which I have already determined the distance along the x and y planes from the original position (for other logic).
So I have used them to determine the angle from the original position, looking for 45-degree angles (within a variance). What I want to do is return the average position at exactly 45 degrees of the secondary position.
Just a snippet of the code below.
//calculate angle of mouse position from buildpoint
float radAngle = Mathf.Atan2(xDistance, yDistance);
float angle = Mathf.Rad2Deg * radAngle;
//check if angle is 45 degrees within tolerance
if (angle > 41 && angle < 49)
{
This is already stretching my math abilities (and its 11pm and my eyes feel like they are going to pop lol). But just looking for some ideas on a) if I can approach this logic in a better way and b) how to determine that clamped 45 degree angle of the second position?
Thanks!vector2anglesmathsTue, 05 Jan 2021 15:17:57 GMTinvisagecan somebody explain to me what is going on in this script ??
http://answers.unity.com/questions/1782129/can-somebody-explain-to-me-what-is-going-on-in-thi.html
in the code below planet.init calls the tile.init().
Context: The Planet class is fed a data object containing information about the planet to spawn, the main one being the radius (how many tiles deep it goes). The same amount of circular strips are then created by spawning a number of tiles depending on the circumference per strip (the farther out it goes, the more tiles are needed to not make the sprites seem stretched), and for every tile, a new mesh is created as shown in the video. It's just a quad-strip where the vertices are snapped to a certain radius from the center of the planet. The sprites are just used as textures on top of that quad-strip by letting the uv-coordinates run from (0,0) to (1,1) for every tile
planet.init() :
public void Init(Level level, Pickup[] pickupPrefabs)
{
float planetScale = (level.RowCount + YOffset - 1) * 2 + 0.5f;
_planetSphere.localScale = new Vector3(planetScale, planetScale, 1);
_planetSphereBackground.localScale = new Vector3(planetScale, planetScale, 1);
float totalRadius = level.TotalRadius;//.RowCount + YOffset - 1;
Tiles = new List<Tile>();
for (int i = 0; i < level.RowCount; i++)
{
float rowRadius = i + YOffset;
float circumference = 2 * Mathf.PI * rowRadius;
int rowTileCount = Mathf.RoundToInt(circumference / TileWidth);
Tile tilePrefab = i == level.RowCount - 1 ? _grassPrefab : _dirtPrefab;
for (int j = 0; j < rowTileCount; j++)
{
Tile tile = Instantiate(tilePrefab, transform);
tile.Init(j, rowRadius, rowTileCount, 1f, planetBar);
Tiles.Add(tile);
}
}
Tile.init() :
public void Init(int xIndex, float rowY, int rowTileCount, float rowHeight, Bar planetBar)
{
this.planetBar = planetBar;
mesh = new Mesh();
List<Vector3> vertices = new List<Vector3>();
List<int> indices = new List<int>();
List<Vector2> uvs = new List<Vector2>();
float minX = (float)xIndex / rowTileCount;
float maxX = (xIndex + 1f) / rowTileCount;
float minY = rowY;
float maxY = minY + rowHeight;
for(int i = 0; i < HorizontalVertexCount; i++)
{
float t = (float)i / (HorizontalVertexCount - 1);
float x = Mathf.Lerp(minX, maxX, t);
Vector3 vertTop = new Vector3(maxY * Mathf.Cos(x * Mathf.PI * 2f), maxY * Mathf.Sin(x * Mathf.PI * 2f)) - transform.position;
vertices.Add(vertTop);
uvs.Add(new Vector2(t, 1f));
center += vertTop;
Vector3 vertBottom = new Vector3(minY * Mathf.Cos(x * Mathf.PI * 2f), minY * Mathf.Sin(x * Mathf.PI * 2f)) - transform.position;
vertices.Add(vertBottom);
uvs.Add(new Vector2(t, 0f));
center += vertBottom;
if(i > 0)
{
int vertexCount = vertices.Count - 1;
indices.Add(vertexCount - 3);
indices.Add(vertexCount - 2);
indices.Add(vertexCount - 1);
indices.Add(vertexCount - 1);
indices.Add(vertexCount - 2);
indices.Add(vertexCount);
}
}
center /= vertices.Count;
mesh.vertices = vertices.ToArray();
mesh.triangles = indices.ToArray();
mesh.uv = uvs.ToArray();
up = center.normalized;
_textureFilter.mesh = mesh;
_colorMeshFilter.mesh = mesh;
_backgroundMeshFilter.mesh = mesh;
}
MORE SPECIFICALLY, i want to understand how vertTop and vertBottom are created in Tile.init method ??meshesmesh verticesmesh manipulationmathsWed, 21 Oct 2020 08:59:18 GMTFineBriskError when importing mathematics
http://answers.unity.com/questions/1777196/error-when-importing-mathematics.html
When I try to import mathematics it throws me an error saying that
_
'' error CS0234: The type or namespace name 'Mathematics' does not exist in the namespace 'Unity' (are you missing an assembly reference?)''.
'
_
I tried, Using System.Mathematics, Using Unity.Mathematics I also tried by typing Math instead of Mathematics. Idk why this is throwing an error,
I use Notepad++ for scripting.
[1]: /storage/temp/168619-screenshot-179.pngunity 5mathmathf.clampmathsSat, 03 Oct 2020 14:14:25 GMTfamestar1236Need help generating points around an object.
http://answers.unity.com/questions/1760180/need-help-generating-points-around-an-object.html
Hello, recently i have been trying to create a script that generates points around an object in 3D on the X and Z planes depending on its size. The changing sizes of the objects will always be integers so no floating points.
I cannot for the life of me figure out how to generate these points around my object, and i was wondering if anyone could help me with my problem. I have attached an image where the points(blue x's) should be with the black boxes representing the object.
![alt text][1]
[1]: /storage/temp/165172-help.pngc#generationmathsMon, 10 Aug 2020 14:39:03 GMTrhubbard95Verlet Elastic Collision
http://answers.unity.com/questions/1747783/verlet-elastic-collision.html
Hey all, I'm working on a game and over the last few days I've taken a script from [here][1] about making rope bridges using verlet integration. So far I've added a 2D edge collider to the object and it all works fine, currently it just creates an object at the Collison point and gets the index of said point. What I'm aiming to do is have an object (eg. My square player) move along it like a ground and I want the shape of the rope to alter accordingly. I was thinking of having an elasticity variable and getting the mass and gravity force from the players rigidbody but I can't think of how to do this. My script is below:
public Transform StartPoint;
public Transform EndPoint;
public bool useCollider = true;
private LineRenderer lineRenderer;
private List<RopeSegment> ropeSegments = new List<RopeSegment>();
public float ropeSegLen = 0.25f;
public int segmentCount = 35;
public float lineWidth = 0.1f;
//Sling Shot
bool moveToMouse = false;
Vector3 mousePositionWorld;
int indexMousePos;
//Gameobject following
//public GameObject followObject;
public EdgeCollider2D edgeCollider;
// Use this for initialization
void Start()
{
this.lineRenderer = this.GetComponent<LineRenderer>();
Vector3 ropeStartPoint = StartPoint.position;
for (int i = 0; i < segmentCount; i++)
{
this.ropeSegments.Add(new RopeSegment(ropeStartPoint));
ropeStartPoint.y -= ropeSegLen;
}
if (useCollider && edgeCollider != null)
{
edgeCollider.enabled = true;
edgeCollider.edgeRadius = lineWidth / 2;
}
else
edgeCollider.enabled = false;
}
// Update is called once per frame
void Update()
{
this.DrawRope();
if (Input.GetMouseButtonDown(0))
{
this.moveToMouse = true;
}
else if (Input.GetMouseButtonUp(0))
{
this.moveToMouse = false;
}
Vector3 screenMousePos = Input.mousePosition;
float xStart = StartPoint.position.x;
float xEnd = EndPoint.position.x;
this.mousePositionWorld = Camera.main.ScreenToWorldPoint(new Vector3(screenMousePos.x, screenMousePos.y, 10));
float currX = this.mousePositionWorld.x; //followObject.transform.position.x
float ratio = (currX - xStart) / (xEnd - xStart);
if (ratio > 0)
{
this.indexMousePos = (int)(this.segmentCount * ratio);
}
}
private void FixedUpdate()
{
this.Simulate();
}
private void OnCollisionEnter2D(Collision2D other)
{
int closestIndex = 805;
float closestDist = float.MaxValue;
for (int i = 0; i < edgeCollider.points.Length; i++)
{
Vector2 edgePoint = edgeCollider.points[i];
float thisDist = Vector2.Distance(edgePoint, other.GetContact(0).point);
if (thisDist < closestDist)
{
closestDist = thisDist;
closestIndex = i;
}
}
#region TESTING //!REMOVE LATER
print(closestIndex);
GameObject go = new GameObject();
go.transform.position = edgeCollider.points[closestIndex];
go.name = "Collision w/ Point " + closestIndex;
#endregion
}
private void Simulate()
{
// SIMULATION
Vector2 forceGravity = new Vector2(0f, -1f);
for (int i = 1; i < this.segmentCount; i++)
{
RopeSegment firstSegment = this.ropeSegments[i];
Vector2 velocity = firstSegment.posNow - firstSegment.posOld;
firstSegment.posOld = firstSegment.posNow;
firstSegment.posNow += velocity;
firstSegment.posNow += forceGravity * Time.fixedDeltaTime;
this.ropeSegments[i] = firstSegment;
}
//CONSTRAINTS
for (int i = 0; i < 50; i++)
{
this.ApplyConstraint();
}
}
private void ApplyConstraint()
{
//Constrant to First Point
RopeSegment firstSegment = this.ropeSegments[0];
firstSegment.posNow = this.StartPoint.position;
this.ropeSegments[0] = firstSegment;
//Constrant to Second Point
RopeSegment endSegment = this.ropeSegments[this.ropeSegments.Count - 1];
endSegment.posNow = this.EndPoint.position;
this.ropeSegments[this.ropeSegments.Count - 1] = endSegment;
for (int i = 0; i < this.segmentCount - 1; i++)
{
RopeSegment firstSeg = this.ropeSegments[i];
RopeSegment secondSeg = this.ropeSegments[i + 1];
float dist = (firstSeg.posNow - secondSeg.posNow).magnitude;
float error = Mathf.Abs(dist - this.ropeSegLen);
Vector2 changeDir = Vector2.zero;
if (dist > ropeSegLen)
{
changeDir = (firstSeg.posNow - secondSeg.posNow).normalized;
}
else if (dist < ropeSegLen)
{
changeDir = (secondSeg.posNow - firstSeg.posNow).normalized;
}
Vector2 changeAmount = changeDir * error;
if (i != 0)
{
firstSeg.posNow -= changeAmount * 0.5f;
this.ropeSegments[i] = firstSeg;
secondSeg.posNow += changeAmount * 0.5f;
this.ropeSegments[i + 1] = secondSeg;
}
else
{
secondSeg.posNow += changeAmount;
this.ropeSegments[i + 1] = secondSeg;
}
//*
Vector2[] colliderPoints = new Vector2[this.segmentCount];
colliderPoints[i] = this.ropeSegments[i].posNow;
if (this.moveToMouse && indexMousePos > 0 && indexMousePos < this.segmentCount - 1 && i == indexMousePos)
{
RopeSegment thisSegment = this.ropeSegments[i];
RopeSegment nextSegment = this.ropeSegments[i + 1];
thisSegment.posNow = new Vector2(this.mousePositionWorld.x, this.mousePositionWorld.y);
nextSegment.posNow = new Vector2(this.mousePositionWorld.x, this.mousePositionWorld.y);
// thisSegment.posNow = new Vector2 (this.followObject.transform.position.x, this.followObject.transform.position.y);
// nextSegment.posNow = new Vector2 (this.followObject.transform.position.x, this.followObject.transform.position.y);
this.ropeSegments[i] = thisSegment;
this.ropeSegments[i + 1] = nextSegment;
}
if (edgeCollider.points.Length == 0)
print("**NULL**");
else
edgeCollider.points[i] = colliderPoints[i];
}
}
private void DrawRope()
{
float lineWidth = this.lineWidth;
lineRenderer.startWidth = lineWidth;
lineRenderer.endWidth = lineWidth;
Vector3[] ropePositions = new Vector3[this.segmentCount];
for (int i = 0; i < this.segmentCount; i++)
{
ropePositions[i] = this.ropeSegments[i].posNow;
}
lineRenderer.positionCount = ropePositions.Length;
lineRenderer.SetPositions(ropePositions);
if (useCollider)
CreateColliders();
}
private void CreateColliders()
{
Vector2[] colliderPoints = new Vector2[this.segmentCount];
for (int i = 0; i < this.segmentCount; i++)
{
colliderPoints[i] = this.ropeSegments[i].posNow;
}
edgeCollider.points = colliderPoints;
}
public struct RopeSegment
{
public Vector2 posNow;
public Vector2 posOld;
public RopeSegment(Vector2 pos)
{
this.posNow = pos;
this.posOld = pos;
}
}
My posts barely get read but if anyone sees this and helps I would be so appreciative, thanks in advance!
[1]: https://www.youtube.com/watch?v=k32g4ujzxP0unity 2dropeedgemathselasticFri, 03 Jul 2020 04:36:46 GMTAsclepiiusUnknownAlign objects to differently sized grids
http://answers.unity.com/questions/1741775/align-objects-to-differently-sized-grids.html
I am trying to make it so that objects can align to a grid on my 2D game. In my game you can adjust the scale of objects, so just using mathf.round wasn't enough as objects would be put in the center of each grid square and they would be spaced apart if the scale was below 1. The way I fixed this was doing this:
Vector3 currentPos = gameObject.transform.position;
gameObject.transform.position = new Vector2(Mathf.Round(currentPos.x * (1/scale)) / scale,Mathf.Round(currentPos.y * (1/scale)) / scale;
But, this didn't work for me the way I wanted to because objects then wouldn't align with each other correctly. ![alt text][1]
[1]: /storage/temp/161913-screenshot-58.png
Instead of the grids they were aligning to just being the original grid but with differently sized grid squares, they seem to have some offset. This has been bothering me for a while and I haven't been able to find a situation. How do I fix this?vector2mathsroundingSun, 14 Jun 2020 01:56:55 GMTChazzwazzlerdetermine that the spinning motion is "CW" or "CCW"
http://answers.unity.com/questions/1737473/determine-that-the-spinning-motion-is-cw-or-ccw.html
I have an object spinning on its axis how can I determine that the spinning motion is "CW" or "CCW".physicsdirectionvectorcalculationmathsTue, 02 Jun 2020 08:13:50 GMTmian_abdulCouping Navmesh and animations
http://answers.unity.com/questions/1711695/couping-navmesh-and-animations.html
I am tring to understand unity documentation code but I am stuck at a dot Product
link : https://docs.unity3d.com/Manual/nav-CouplingAnimationAndNavigation.html
using UnityEngine;
using UnityEngine.AI;
[RequireComponent (typeof (NavMeshAgent))]
[RequireComponent (typeof (Animator))]
public class LocomotionSimpleAgent : MonoBehaviour {
Animator anim;
NavMeshAgent agent;
Vector2 smoothDeltaPosition = Vector2.zero;
Vector2 velocity = Vector2.zero;
void Start ()
{
anim = GetComponent<Animator> ();
agent = GetComponent<NavMeshAgent> ();
// Don’t update position automatically
agent.updatePosition = false;
}
void Update ()
{
Vector3 worldDeltaPosition = agent.nextPosition - transform.position;
// Map 'worldDeltaPosition' to local space
float dx = Vector3.Dot (transform.right, worldDeltaPosition);
float dy = Vector3.Dot (transform.forward, worldDeltaPosition);
Vector2 deltaPosition = new Vector2 (dx, dy);
// Low-pass filter the deltaMove
float smooth = Mathf.Min(1.0f, Time.deltaTime/0.15f);
smoothDeltaPosition = Vector2.Lerp (smoothDeltaPosition, deltaPosition, smooth);
// Update velocity if time advances
if (Time.deltaTime > 1e-5f)
velocity = smoothDeltaPosition / Time.deltaTime;
bool shouldMove = velocity.magnitude > 0.5f && agent.remainingDistance > agent.radius;
// Update animation parameters
anim.SetBool("move", shouldMove);
anim.SetFloat ("velx", velocity.x);
anim.SetFloat ("vely", velocity.y);
GetComponent<LookAt>().lookAtTargetPosition = agent.steeringTarget + transform.forward;
}
void OnAnimatorMove ()
{
// Update position to agent position
transform.position = agent.nextPosition;
}
}
this three lines I can't grasp:
float dx = Vector3.Dot (transform.right, worldDeltaPosition);
float dy = Vector3.Dot (transform.forward, worldDeltaPosition);
Vector2 deltaPosition = new Vector2 (dx, dy);
Why they are using Dot product and for what purpose?mathsFri, 27 Mar 2020 07:26:43 GMTnickk2002Need help putting integral function into C#
http://answers.unity.com/questions/1704626/need-help-putting-integral-function-into-c.html
Hi, I'm trying to put this function into one of my scripts, but I don't know how to do the integrals in C#. Hopefully someone here can help
![alt text][1]
[1]: /storage/temp/153601-probabilityfromz.png
ThanksmathmathssciptingWed, 04 Mar 2020 00:09:16 GMTMagmawFiring A Projectile Along A Parabola
http://answers.unity.com/questions/1701548/firing-a-projectile-along-a-parabola.html
Hey,
My mathematical ability is horrible, at best. I am genuinely trying to improve it when I can. I'm making a boat game (3D), and am trying to fire my projectile along a parabola without the physics system at the moment. Forgive my naivety but In all honesty I thought i could just use the Wiki page formulae, but I was horribly wrong.
How do I fire and also take into consideration how high my boat turret is facing?
----------
Current code:
float t = 0;
for (int i = 0; i < resolution; i++)
{
float ang = transform.rotation.x * Mathf.Deg2Rad;
float v = 20f;
float x = v * t * Mathf.Cos(ang);
float y = v * t * Mathf.Sin(ang) - 0.5f * 9.18f * Mathf.Pow(t, 2);
Vector3 porabPoint = transform.position + new Vector3(x, y, 0);
Gizmos.DrawSphere(porabPoint, 0.2f);
t += 0.01f;
}
I presume something is wrong with my angle calculation? Should I be using atan2?
Thanks!c#mathmathsparabolaThu, 20 Feb 2020 17:58:08 GMTDaedricWolf19Calculate speed for distance with bpm
http://answers.unity.com/questions/1681272/calculate-speed-for-distance-with-bpm.html
Ok, this must be a really _wierd_ one, but the thing is: I'm making a pong-like game where BPM is essential because I want that every beat, the ball collide with the players' wall; __I already fixed any problem that can lead to the loss of rhythm__ (such as position change or maintaining the speed of x constant), that is no problem, but the thing is, __how can I calculate the speed that I need for the ball to collide every beat, knowing how many bpm the song is?__
More than a Unity question, is more a math question...
If you need more info, just ask. Thanks!physics2dspeedmathmathscalculationsSun, 01 Dec 2019 07:01:25 GMTdeveloperation1How to get the corrrect Stereo Projection matrices
http://answers.unity.com/questions/1679616/how-to-get-the-corrrect-stereo-projection-matrices.html
I have tried the method:
Camera.GetStereoNonJitteredProjectionMatrix(Camera.StereoscopicEye.Left/Right);
However, the matrix that it gives me is actually different than the one used on the GPU. For a comparison, I used a GPU readback to get the projection matrix from the Vive Pro, and compared that with the matrix that the camera method gave me:
// Camera method, left eye:
0.77925 0.00000 -0.05615 0.00000
0.00000 0.70090 0.00480 0.00000
0.00000 0.00000 -1.00060 -0.60018
0.00000 0.00000 -1.00000 0.00000
// Camera method, right eye:
0.78300 0.00000 0.05547 0.00000
0.00000 0.70472 0.00192 0.00000
0.00000 0.00000 -1.00060 -0.60018
0.00000 0.00000 -1.00000 0.00000
// GPU Readback, left eye:
0.77925f, 0.00000f, -0.05615f, 0.00000f
0.00000f, -0.70090f, -0.00480f, 0.00000f
0.00000f, 0.00000f, 0.00030f, 0.30009f
0.00000f, 0.00000f, -1.00000f, 0.00000f
// GPU Readback, right eye:
0.78300f, 0.00000f, 0.05547f, 0.00000f
0.00000f, -0.70472f, -0.00192f, 0.00000f
0.00000f, 0.00000f, 0.00030f, 0.30009f
0.00000f, 0.00000f, -1.00000f, 0.00000f
These are somehow different, so I'm wondering which additional calculations Unity does before sending it to the GPU. If I know that then I could implement those steps myself and be able to overwrite the Projection matrix in for VR.graphicsmathmatrixmathsSun, 24 Nov 2019 18:54:09 GMTMarco_StoneHow to calculate distance between sphere and tangent plane for determining grounded state?
http://answers.unity.com/questions/1679971/how-to-calculate-distance-between-sphere-and-tange.html
I need to cast a series of rays from the underside of a capsule collider which will determine how grounded said collider is for a 3D platformer character (it is not a character controller, it is a rigidbody). I have set up a for loop inside of a for loop like I would do with a box collider, but now I need to determine the Y distance between the very bottom of the collider and the surface of collider at each x and z grid point. The code would go in the y section of rayOrigin's new Vector3.
public float rayDist = 0.1f;
public int rayLoops = 4;
Rigidbody rb;
Collider col;
Vector3 size;
Vector3 colCore;
bool CheckGrounded()
{
bool yep = false;
//create bugfixing layer mask
int layerMask = 1 << 8;
layerMask = ~layerMask;
int rayCon = rayLoops * 2;
float colRad = size.x;
for (int xLoop = -rayLoops; xLoop <= rayLoops; xLoop++)
{
for (int zLoop = -rayLoops; zLoop <= rayLoops; zLoop++)
{
Vector3 rayOrigin = transform.position + new Vector3( ((size.x / rayCon) * xLoop),-(size.y / 2),((size.z / rayCon) * zLoop) ) - colCore;
bool testGrid = Physics.Raycast(rayOrigin, -Vector3.up * rayDist, rayDist, layerMask);
if (testGrid) { yep=true; }
Debug.DrawRay(rayOrigin, -Vector3.up * rayDist, Color.red, Time.deltaTime, false);
}
}
return (yep);
}
I understand there may be a simpler solution that I'm missing, but I'm missing it, so I need to know how to adjust this code.raycastingplatformerfor-loopcapsulecollidermathsSun, 24 Nov 2019 14:25:35 GMTFifthPlanetSin wave cycle skipping when world resets
http://answers.unity.com/questions/1679937/sin-wave-cycle-skipping-when-world-resets.html
Hello friends,
Please forgive me if this question isn't presented correctly in any way.
I am creating an ocean of waves using sine based off a world position using a combination of these two excellent tutorials:
https://www.habrador.com/tutorials/unity-boat-tutorial/4-waves-endless-ocean/
and
https://catlikecoding.com/unity/tutorials/flow/waves/
I have a player ship which, when it reaches a certain distance from zero, resets itself and the surrounding map to near zero to avoid floating point issues using this script:
https://wiki.unity3d.com/index.php/Floating_Origin
When this happens the waves skip, as I'm guessing the floating point reset causes them to be out of sync, or to jump a few steps in their cycle. I have looked at a lot of sine stuff in an attempt to understand what is happening and think the solution might have something to do with phase shifts or phase distance but sadly my meagre grasp of maths *blames teachers* has left me a bit stranded. Can anyone help make the wave transition smooth?
Thanks in advance for your timetrigonometrymathssinSun, 24 Nov 2019 10:04:26 GMTcolasterCan I include Math.NET Numerics in some code of my asset that I'm going to sell in the assets store?
http://answers.unity.com/questions/1677212/can-i-include-mathnet-numerics-in-some-code-of-my.html
I'm also including a dll and other resources in the plugins folder to make the library work.assetasset storemathsSun, 10 Nov 2019 18:45:50 GMTMauricioRHIssues 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 GMTServail