Questions in topic: "math"
http://answers.unity.com/questions/topics/single/160.html
The latest questions for the topic "math"How to transform/rotate a vector onto the same plane as another vector
http://answers.unity.com/questions/1872216/how-to-transformrotate-a-vector-onto-the-same-plan.html
I have 2 vectors, a predetermined vector and a vector with random x and z values. The random vector starts with a y value of 0, but I need to set it to a value that is in the same plane as the predetermined vector.
For example, I have the predetermined vector (3, 1, 2) and a vector with values (2,0-2). How can I make sure the effect in the below image is achieved? These are non-normalized vectors, in my game the vectors are normalized.
![alt text][1]
[1]: /storage/temp/188940-fromtovector.pngvector3mathtrigonometryFri, 19 Nov 2021 20:11:31 GMTarjenvklaverenMake a navmesh object start moving in a circle around an object
http://answers.unity.com/questions/1869981/make-a-navmesh-object-start-moving-in-a-circle-aro.html
When my enemy gets within so close to the player it is supposed to start to circle around it. I kind of have this working as I am able to get it to circle around the player without any issue, however what I can not get is for the enemy to start in the correct spot on the circle. As in, when the enemy starts making its circle I want it to start where it is. Instead it moves to a random position on the circle then starts. This is my code so far.
> targetDir = mEnemy.transform.position - mEnemy.myTarget.transform.position;
targetDir.y = 0;
Debug.DrawRay(mEnemy.myTarget.transform.position, targetDir * 5, Color.red, 20f);
Debug.DrawRay(mEnemy.myTarget.transform.position, mEnemy.myTarget.transform.forward * 5f, Color.red, 20f);
float angle = Vector3.Angle(mEnemy.myTarget.transform.forward, targetDir);
Debug.Log(angle);
theta = angle * (Mathf.PI / 180);
Debug.Log(theta);
x = Mathf.Cos(theta) * 5 + mEnemy.myTarget.transform.position.x;
y = mEnemy.transform.position.y;
z = Mathf.Sin(theta) * 5 + mEnemy.myTarget.transform.position.z ;
pos.x = x;
pos.y = y;
pos.z = z;
mEnemy.agent.SetDestination(pos);
I really don't understand why this is not working as my debug tests are showing me that I do indeed have the correct theta. What is wrong with my math?positionnavmeshmathanglescircleSat, 06 Nov 2021 20:26:54 GMTlink111348Rotate and proportionally scale a vector
http://answers.unity.com/questions/1869089/rotate-and-proportionally-scale-a-vector.html
Hello, how to rotate a vector and scale its magnitude proportional to the angle to get a for example constant value on the y-axis?
![vectors][1]
[1]: /storage/temp/188146-1.pngmathvectorsrotationsMon, 01 Nov 2021 12:14:44 GMTPCSzymikHow to draw the front view and top view of the model
http://answers.unity.com/questions/1868909/how-to-draw-the-front-view-and-top-view-of-the-mod.html
I thought of getting each vertex and projecting them onto the matrix of the front view and top view, but I don't know how to get the vertices to line up correctly.
I did try keywords like wireframe shader/geom shader.
But I either can't deal with the triangular lines or how the lines should be connected.
For example, in the model below, I want to draw it like the one on the right.
![alt text][1]
[1]: /storage/temp/188110-无标题.pngshadermathprojectionSun, 31 Oct 2021 04:35:29 GMTlonely2015quaternion - rotate camera based on original facing at scene start?
http://answers.unity.com/questions/1864803/quaternion-rotate-camera-based-on-original-facing.html
It's my first time really trying to do something with quaternion math. There are many tutorials out there showing how one can get a camera to rotate with the device's gyroscope, but I'm trying to do something one step farther.
After following various tutorials, the initial facing of the camera in my game is dependent on how I'm holding my phone at the time the scene loads. This is NOT what I want. I would like the game camera to always **start** as I have it set in the scene designer - for example if the player should start facing a fire, they should always start facing the fire no matter how they're holding the phone when the scene loads. Then as they turn the phone, the camera rotates away from the fire to show the rest of the scene. When they return to their original real world position, they're again looking at the fire.
Here is my latest attempt, where I try sampling the initial camera and gyroscope quaternions and then basing future rotations on the "delta" of the gyroscope's rotation. Put simply, it doesn't work. What am I doing wrong here? I assume it's a math problem.
public class RotateByDeviceRotation : MonoBehaviour
{
private Quaternion originalObjectRotation;
private Quaternion originalGyroRotation;
// Start is called before the first frame update
void Start()
{
if(SystemInfo.supportsGyroscope)
{
Input.gyro.enabled = true;
this.originalObjectRotation = transform.rotation;
this.originalGyroRotation = Input.gyro.attitude;
}
}
// Update is called once per frame
void Update()
{
if(Input.gyro.enabled)
{
transform.rotation = this.originalObjectRotation * GyroToUnity((this.originalGyroRotation * Quaternion.Inverse(Input.gyro.attitude)));
}
}
private static Quaternion GyroToUnity(Quaternion q) //from unity docs
{
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
}rotationquaternionmathgyroscopequaternionsWed, 06 Oct 2021 04:01:44 GMTBigScaryHelp with Delaunay Triangulation using specific library
http://answers.unity.com/questions/1864409/help-with-delaunay-triangulation-using-specific-li.html
So I'm still a bit of an amateur when it comes to C#, and I recognize that this is a bit of a broad question not entirely related to Unity, but I was hoping someone would be kind enough to spare me the time to help anyway...
----------
So. I'm currently trying to work on random dungeon generation, using a method some of you may have heard of before using randomly positioned adjacent (but not overlapping) cubes, where one of the steps involves creating a graph between hub rooms using Delaunay Triangulation.
However, I'm honestly really stuck. I'm using the Delaunator-Sharp library, and I can't for the life of me figure out how to go about using it. It's been imported and I'm including it in my C#/.cs file, but I'm unsure how to go about generating the data from my array of points. I've also looked at the page with the Java documentation, and despite knowing Java better than C#, I still find myself stuck.
I did also ask a friend about this, but unfortunately they're a bit too busy to help.
Can anyone give me a hand?
[Here is the library][1].
Thanks.
[1]: https://github.com/nol1fe/delaunator-sharpc#mathprocedural generationtriangulationMon, 04 Oct 2021 07:04:35 GMTjolechallinor3How to detect a flat area in a mesh?
http://answers.unity.com/questions/1863723/how-to-get-flat-area-in-a-mesh.html
I'm trying to get the flat surface of a mesh. Basically, I will raycast to the mesh and get a particular point.
First thing, I need to get the surface area like a square on the given mesh where I am raycasting, then I need to calculate if that area is flat or not.
I got this below code for detecting at least one flat surface in a mesh.
bool HasFlatshadedSurface(Mesh m)
{
Vector3[] normals = m.normals;
int[] indices = m.triangles;
int triangleCount = indices.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
Vector3 n1 = normals[indices[i * 3]];
Vector3 n2 = normals[indices[i * 3 + 1]];
Vector3 n3 = normals[indices[i * 3 + 2]];
if (n1 == n2 && n1 == n3)
return true;
}
return false;
}
But, my case is different where as I am trying to get a particular area which I need to scan and get if it is flat or not. How can I do this?meshmathmeshfiltertrianglesmesh verticesThu, 30 Sep 2021 05:27:44 GMTNavy_SealsMove an object in an arc towards a location
http://answers.unity.com/questions/1862704/move-an-object-in-an-arc-towards-a-location.html
I'm trying to make a rocket object that arcs to the desired location and I've tried many solutions and it just won't work. `
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float distance;
public float speed = 0.25f;
public int damage = 40;
public Rigidbody2D rb;
public GameObject impactEffect;
public Vector3 target;
public Vector3 player;
public bool CanGo = true;
public bool Switch = false;
public float step;
public Vector3 Arc;
private Vector3 vectorToTarget;
public Vector3 Arc_M;
public GameObject Target_Obj;
// Use this for initializatio
private void FixedUpdate()
{
Vector3 vectorToTarget = target - transform.position;
float angle = (Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg) - 90;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 3.5f);
Debug.Log("arc " + Arc);
step = speed * Time.deltaTime;
Arc = Vector3.MoveTowards(transform.position, target, step);
Arc = Vector3.Normalize(Arc);
if (!Switch)
{
if (CanGo)
{
Arc_M = new Vector3(Arc.x * 3f, Arc.y * 3f, 0);
Arc_M = Vector3.Normalize(Arc_M);
transform.position = Arc_M;
}
}
else
{
Arc_M = new Vector3(Arc.x * 0.4f, Arc.y * 0.4f, 0);
Arc_M = Vector3.Normalize(Arc_M);
transform.position = Arc_M;
Debug.Log("switched");
}
distance = Vector3.Distance(target, transform.position);
if(transform.position.x == target.x && transform.position.y == target.y)
{
Destroy(this.gameObject);
}
else if (distance <= 0.5f)
{
Destroy(this.gameObject);
}
}
public IEnumerator Switch1()
{
yield return new WaitForSeconds(1.8f);
//Switch = true;
//speed = 2f;
yield return new WaitForSeconds(3.2f);
//speed = 0.75f;
Switch = false;
}
private void Start()
{
CanGo = true;
Debug.Log("start");
StartCoroutine(Switch1());
Target_Obj = GameObject.FindWithTag("Target");
}
public void SetTarget(Vector3 pos, Vector3 Player)
{
player = Player;
target = pos;
Debug.Log("pos " + pos);
Debug.Log("target " + target);
}
} `unity 2dmatharcFri, 24 Sep 2021 03:38:13 GMTAd1min0How to continiously move objects in a filled circle formations
http://answers.unity.com/questions/1862296/how-to-continiously-move-objects-in-a-filled-circl.html
Hey everyone,
private void ArrowPositionUpdater()
{
int arrowCount = transform.childCount;
float angleSelection = Mathf.PI * 2f / arrowCount;
for (int i = 0; i < arrowCount; i++)
{
Transform child = transform.GetChild(i);
float angle = i * angleSelection;
Vector3 arrowPosition = transform.position + new Vector3(rx * Mathf.Cos(angle),
ry * Mathf.Sin(angle) * Mathf.Sqrt(i),
0f);
child.position = arrowPosition;
}
}
with the method above I am able to continuously move objects in a circle formation, however I would like to fill that circle. I want objects to move in a filled circle formation.
Can you please give me an idea on this ?
Thanks!mathWed, 22 Sep 2021 06:11:51 GMTalpermisirliHow to find the center of mass from capsulecast
http://answers.unity.com/questions/1860879/how-to-find-the-center-of-mass-from-capsulecast.html
Is there an easy way to find the center of mass from a capsulecast, or should I find the geometric center of it?physicsraycastmathgeometrycapsulecastMon, 13 Sep 2021 21:15:32 GMTRhinoPakcalculate position and rotation relatively to shpere (Planet)
http://answers.unity.com/questions/1858819/calculate-position-and-rotation-relatively-to-shpe.html
Hi, Im trying come up with how spawn objects in random position (trees, stones) with right rotation relativly planet (sphere). Can anyone help me ?
![alt text][1]
[1]: /storage/temp/185720-image-1.jpg3dmathalgorithmFri, 03 Sep 2021 09:36:34 GMTalbor09How to split velocity into two smaller vectors at a chosen degree?
http://answers.unity.com/questions/1857299/how-to-split-velocity-into-two-smaller-vectors-at.html
What I want is to go from a velocity of a rigidbody and then split that velocity into two smaller velocity's that go roughly the same way just at a higher or lower angle. I tried using SohCahToa but it only worked when the object was going a specific direction. The black arrow is the velocity and the red is what I want to find. Thanks.mathvectorFri, 27 Aug 2021 03:36:07 GMTMachinoDudeHow to calculate corners of near clip rect from Projection Matrix?
http://answers.unity.com/questions/1856946/how-to-calculate-corners-of-near-clip-rect-from-pr.html
[Edit: The errors in my assumptions were: 1. confusion between NDC and clip space;
And, 2. assuming that clip space goes from [-1,-1,0] ro [+1,+1,+1]. It goes from [-1,-1,-1] to [+1,+1,+1].
Therefore, the coordinates of the bottom-left of near clip rect in clip space are (-1,-1,-1), and so on...]
Given a projection matrix (with no assumptions about what kind of projection matrix it is, could be oblique/off-center, etc), I attempted to get the frustum corners as `InverseProjectionMatrix * {corners in NDC space}`, however the results seem to be incorrect. Here is the code I used:
/// This is what I need to work
void GetFrustumCornersFromCameraMatrix()
{
// The frustum rect at near clip plane is the inverse projection of a rectangle
// with bounds [-1,-1,0] to [+1,+1,0] in normalized device coordinates.
Camera cam = this.GetComponent<Camera>();
var invMat = cam.nonJitteredProjectionMatrix.inverse;
var bottomLeft = invMat * new Vector4(-1, -1, 0, 1);
var topRight = invMat * new Vector4(1, 1, 0, 1);
bottomLeft /= bottomLeft.w;
topRight /= topRight.w;
this.left = bottomLeft.x;
this.right = topRight.x;
this.bottom = bottomLeft.y;
this.top = topRight.y;
}
/// For comparison purposes only - this works perfectly
void GetFrustomCornersFromCameraSettings()
{
Camera cam = this.GetComponent<Camera>();
float frustumHeight =
2.0f * cam.nearClipPlane
* Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad);
var frustumWidth = frustumHeight * cam.aspect;
this.left = -frustumWidth * 0.5f;
this.right = frustumWidth * 0.5f;
this.bottom = -frustumHeight * 0.5f;
this.top = frustumHeight * 0.5f;
}
private void OnDrawGizmos()
{
var matbk = Gizmos.matrix;
Camera cam = this.GetComponent<Camera>();
float radius = 0.02f;
Gizmos.matrix = this.transform.localToWorldMatrix;
Gizmos.DrawSphere(new Vector3(left, top, cam.nearClipPlane), radius);
Gizmos.DrawSphere(new Vector3(left, bottom, cam.nearClipPlane), radius);
Gizmos.DrawSphere(new Vector3(right, top, cam.nearClipPlane), radius);
Gizmos.DrawSphere(new Vector3(right, bottom, cam.nearClipPlane), radius);
Gizmos.matrix = matbk;
}
As you can see from the Gizmos, the returned coordinates are larger than what should be.
(E.g., left should be -0.04430015, but I'm getting back -0.08857372, appears almost double but is not double)
![Gizmos showing larger near clip rect][1]
What am I doing wrong? Thanks in advance.
[1]: /storage/temp/185278-gizmos.pngmathprojection-matrixWed, 25 Aug 2021 08:52:57 GMTsabintHLSL bit shifting
http://answers.unity.com/questions/1852518/hlsl-bit-shifting.html
I have a sprite that I am trying to enable palette swapping on. I've written a tool to iterate over the color values in the sprite and encode the colors palette index within the first(?) two bits in each color value:
ex: pixel index is 21 and the original color value was #a22633 (162, 38, 51)
1. convert 21 to 6 bits: 010101
2. separate those bits into three 2 bit segments: 01 01 01
3. drop the last two bits off each color value and replace them with the bits from each segment
R: 162 => 161 10100010 => 10100001
G: 38 => 37 100110 => 100101
B: 51 => 49 110011 => 110001
The next part is where I'm struggling. I want to be able to read these values in and reconstruct the index inside my fragment shader, but I'm having some difficulty with reading the bits.
I've added the following function to my shader
int CheckBit(float f, float bit, int setValue)
{
float sample = f % bit;
if (sample == 0) return 0;
if (bit == 2 && sample == 1.0) return setValue;
if (sample >= bit/2.0) return setValue;
return 0;
}
and I'm using it like this:
float4 UnlitFragment(Varyings i) : SV_Target
{
float4 mainTex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
float4 pack = mainTex * 255.0f;
int index = 0;
index += CheckBit(pack.r, 2, 16);
index += CheckBit(pack.r, 4, 32);
index += CheckBit(pack.g, 2, 4);
// etc ...
// use the index value to sample color value from our palette
float2 puv = float2(index / 64.0, 0); // palette is a 64x1 sprite
float4 palette = SAMPLE_TEXTURE2D(_PaletteTex, sampler_PaletteTex, puv);
palette.a = mainTex.a;
palette.rgb *= mainTex.a;
return palette;
}
This doesn't appear to be generating the correct index values. I think my bit reading code is off, but I've tried a lot of other methods and none seem to work correctly. I feel like I'm missing something basic.shadersmathhlslMon, 02 Aug 2021 20:41:19 GMTcodeimpossibleMultinomial Distribution in Unity?
http://answers.unity.com/questions/1851629/multinomial-distributions-in-unitymultinomial-dist.html
Hi all,
I'm relatively new to Unity, but with a good deal of programming experience (though not in C#).
I was surprised to find that the Unity scripter only had a built in Uniform distribution, in the form of Random.Range. My question is regarding what the best way is to gain the use of other distributions. I've seen that some people have packaged up some in the Asset store; Gaussian, Exponential, but it's the Multinomial I really want to be able to use.
Surely there must be a way to import other general C# packages? A bit of google-sleuthing suggested something called NuGet might be the way to go?
Very appreciative of any help anyone can provide. Many thanks, Thom
P.S. I'm only doing a few draws at a time so I can't do a multivariate-normal approximation!randommathrandomizerandomizingWed, 28 Jul 2021 20:33:41 GMTTolkamasWheel rotation, what am I doing wrong?
http://answers.unity.com/questions/1851187/wheel-rotation-what-am-i-doing-wrong.html
Ok so I am trying to get a wheel to rotate an object as if it is a wheel of a known diameter and traveling a known distance, and I need to know how much to rotate the object.
<br><br>
My understanding is the equation for that is ( distance / circumference = degrees to rotate ), where circumference = diameter * pi. Except when I try to actually apply that equation the rotations I am getting are tiny compared to the movement.
<br><br>
public class WheelDebug : MonoBehaviour
{
public float MoveSpeed = 1;
public float Diamiter = 1.41f;
// Update is called once per frame
void Update()
{
float distanceMoved = MoveSpeed * Time.deltaTime;
transform.position += Vector3.forward * distanceMoved;
float circumference = Diamiter * Mathf.PI;
float rotationToTravelDistance = distanceMoved / circumference;
transform.rotation *= Quaternion.Euler(rotationToTravelDistance, 0, 0);
}
}
<br>
So based on my understanding, what is happening above is every frame, which occurs ~60 times a second, my object moves MoveSpeed * Time.deltaTime, resulting in the object moving 1 unity unit or meter, per second in game, regardless of framerate.
<br><br>
Since I record it as distanceMoved, I can then plug that into the wheel turn calculation since I know that is the exact distance the object moved this frame, and.... I know what I did wrong.
<br><br>
Posting this anyway so anyone running into the same problemmathcirclewheelTue, 27 Jul 2021 01:15:08 GMTCiberX15Trying match Unity Animation Curve with Hermit Spline. Ger Weird behaviour....
http://answers.unity.com/questions/1851097/trying-match-unity-animation-curve-with-hermit-spl.html
Hello, I'am trying to draw custom graph inside my custom inspector and need to render graph like unity made it. I found that they using Some Sort of Hermit Spline to do it. I generate logarithmic curve and try make it smooth between generate keyframe. But in between of two keyframes Evaluate method from Hermit Spline Get wrong values...
There are my test class for render and debugging. What I am doing wrong? Resolution is just amount of point inside segment between two keyframes
There pic of weird behaviour inside inspector:![alt text][1]
But I Want it to be like this, but smooth and like unity built-in anim curves( I am using them, but can't render properly):![alt text][2]
using System.Collections.Generic;
using UnityEngine;
public class HermitTest : MonoBehaviour
{
public AnimationCurve curve;
public LineRenderer lineRenderer;
private Vector4 parameters;
private int resolution = 2;
public void Start()
{
curve = LogarithmicCurve(new Vector2(0, 1f));
lineRenderer.positionCount = (curve.keys.Length-1)*resolution+curve.keys.Length;
for (int i = 0; i < curve.keys.Length-1; i++)
{
Vector3 p0 = new Vector3(curve.keys[i].time, curve.keys[i].value, curve.keys[i].outTangent);
Vector3 p1 = new Vector3(curve.keys[i+1].time, curve.keys[i+1].value, curve.keys[i+1].inTangent);
parameters = CalculateParameters(p0, p1);
for (int j = 0; j < resolution; j++)
{
float t = (j * 1.0f) / (resolution);
float y = Evaluate(parameters, t);
float x = Mathf.Lerp(p0.x, p1.x, t);
lineRenderer.SetPosition(i*resolution+j, new Vector3(x, 0, y));
}
}
}
private float LogValue(float distance, float minDistance)
{
distance = Mathf.Max(distance, 0.0001f);
return minDistance / distance;
}
private AnimationCurve LogarithmicCurve(Vector2 range)
{
float value, slope, s;
List<Keyframe> keys = new List<Keyframe>();
float step = 2;
range.x = Mathf.Max(range.x, 0.01f);
for (float i = range.x; i < range.y; i *= step)
{
value = LogValue(i, range.x);
s = i / 50f;
slope = (LogValue(i + s, range.x) - LogValue(i - s, range.x)) / (s * 2);
keys.Add(new Keyframe(i, value, slope, slope));
}
value = LogValue(range.y, range.x);
s = range.y / 50f;
slope = (LogValue(range.y + s, range.x) - LogValue(range.y - s, range.x)) / (s * 2);
keys.Add(new Keyframe(range.y, value, slope, slope));
return new AnimationCurve(keys.ToArray());
}
private Vector4 CalculateParameters(Vector3 p1, Vector3 p2)
{
float p1x = p1.x;
float p2x = p2.x;
float p1y = p1.y;
float p2y = p2.y;
float tp1 = p1.z;
float tp2 = p2.z;
float a = (p1x * tp1 + p1x * tp2 - p2x * tp1 - p2x * tp2 - 2 * p1y + 2 * p2y) / (p1x * p1x * p1x - p2x * p2x * p2x + 3 * p1x * p2x * p2x - 3 * p1x * p1x * p2x);
float b = ((-p1x * p1x * tp1 - 2 * p1x * p1x * tp2 + 2 * p2x * p2x * tp1 + p2x * p2x * tp2 - p1x * p2x * tp1 + p1x * p2x * tp2 + 3 * p1x * p1y - 3 * p1x * p2y + 3 * p1y * p2x - 3 * p2x * p2y) / (p1x * p1x * p1x - p2x * p2x * p2x + 3 * p1x * p2x * p2x - 3 * p1x * p1x * p2x));
float c = ((p1x * p1x * p1x * tp2 - p2x * p2x * p2x * tp1 - p1x * p2x * p2x * tp1 - 2 * p1x * p2x * p2x * tp2 + 2 * p1x * p1x * p2x * tp1 + p1x * p1x * p2x * tp2 - 6 * p1x * p1y * p2x + 6 * p1x * p2x * p2y) / (p1x * p1x * p1x - p2x * p2x * p2x + 3 * p1x * p2x * p2x - 3 * p1x * p1x * p2x));
float d = ((p1x * p2x * p2x * p2x * tp1 - p1x * p1x * p2x * p2x * tp1 + p1x * p1x * p2x * p2x * tp2 - p1x * p1x * p1x * p2x * tp2 - p1y * p2x * p2x * p2x + p1x * p1x * p1x * p2y + 3 * p1x * p1y * p2x * p2x - 3 * p1x * p1x * p2x * p2y) / (p1x * p1x * p1x - p2x * p2x * p2x + 3 * p1x * p2x * p2x - 3 * p1x * p1x * p2x));
return new Vector4(a, b, c, d);
}
private float Evaluate(Vector4 parameters, float t)
{
return parameters.x * t * t * t + parameters.y * t * t + parameters.z * t + parameters.w;
}
}
[1]: /storage/temp/184023-screenshot-5.png
[2]: /storage/temp/184024-screenshot-6.pngeditormathanimationcurvesplineMon, 26 Jul 2021 17:27:54 GMTalicewithalex25How can I follow the terrain
http://answers.unity.com/questions/1848897/how-can-i-follow-the-terrain.html
I want to know how I can lerp from my current position, to another position, while hugging the terrain. Imagine I'm doing something like surfing, or skateboarding, where I need to follow the rail...etc. I've tried simply projecting from the location down to the plane to get the projection vector, but this will have problems if it's not flat. If it's bumpy, or if there are slopes, there are problems. Any ideas?c#lerpmathslopesWed, 14 Jul 2021 22:59:31 GMTbdoomUnity isn't adding number the way I want it to.
http://answers.unity.com/questions/1847793/unity-isnt-adding-number-the-way-i-want-it-to.html
I have a program that is a remake of flappy bird. I use a quad behind (which is to the left of the player as obstacles are moving right to left) player to count how many obstacles it made though. Since there will be an obstacle to the top and one to the bottom yet they come at the exact same time, so I just tell it to
<hr>
<code> private void OnPlayerSurvived() => IOHandler.Survived += add; </code><hr>
add is a float of 0.5f. However, it still increments the score counter the same amount as the time the scene has loaded. My hypnosis are:<hr> <ol>
<li>the counter object is not removed during reload.</li>
<li>the whole scene wasn't removed</li>
</ol>
help warranted.mathscene-switchingFri, 09 Jul 2021 18:41:26 GMTHenrys-StudioIntersection of two lines
http://answers.unity.com/questions/1846442/intersection-of-two-lines.html
Hi guys ,
I found a code how to find an intersection point of two lines . I do understand how to find intersection x and y using simultaneous equations. But having hard time understanding the code.
Need a little help, so I am not just copying it.
https://github.com/setchi/Unity-LineSegmentsIntersection/blob/master/Assets/LineSegmentIntersection/Scripts/Math2d.cs
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LineSegmentsIntersection
{
public static class Math2d
{
public static bool LineSegmentsIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, out Vector2 intersection)
{
intersection = Vector2.zero;
var d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
if (d == 0.0f)
{
return false;
}
var u = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
var v = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d;
if (u < 0.0f || u > 1.0f || v < 0.0f || v > 1.0f)
{
return false;
}
intersection.x = p1.x + u * (p2.x - p1.x);
intersection.y = p1.y + u * (p2.y - p1.y);
return true;
}
}
}c#mathvector2intersectionSun, 04 Jul 2021 12:59:02 GMTArtpenCreating an UI GPS map
http://answers.unity.com/questions/1845865/creating-an-ui-gps-map.html
Hello everyone.
First i'm not English so my post will probably have some mistakes.
I'm working on a offline GPS map system working in a UI canvas, i took some screenshots of maps and get the coordinates at the up left and down right corners of each map. My script actually takes all thoses variables and then do some maths to place a marker in the map corresponding to the position of the player. The problem is that it is misplaced to the correct position in the y axis. Here's my script, he got two different lines of code for setting the position of the marker depending of if i'm testing on pc or android.
I think you should only watch at the beginning of the update function where i change the position of my marker cause the other functionality works and i think it's only a math problem.
Thank you for watching.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Android;
using System.IO;
public class gps_locationpoint : MonoBehaviour
{
private float Lat;
private float Lon;
private float factor_x;
private float factor_y;
public Vector2 ul_Corner; //up left corner
public Canvas canvas;
public Vector2 dr_Corner; //down right corner
public Vector2 fakepos; //the position while testing on pc
public bool isUpdating;
private Image image;
float marge;
Transform trans;
private RectTransform self;
public RectTransform map;
public RectTransform offset_obj;
Vector3 TouchStart;
// Start is called before the first frame update
void Start()
{
self = gameObject.transform.GetComponent<RectTransform>();
image = gameObject.transform.parent.GetComponent<Image>();
trans= GetComponent<RectTransform>();
TouchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
// Update is called once per frame
private void Update()
{//this is the calculation for pc testing
trans.position = new Vector3(((map.rect.width*(fakepos.x-ul_Corner.x)/(dr_Corner.x-ul_Corner.x)))*(canvas.scaleFactor)+map.position.x+self.rect.width/2,(((map.rect.height/2*(fakepos.y-ul_Corner.y)/(dr_Corner.y-ul_Corner.y)))*(canvas.scaleFactor))+map.position.y-self.rect.width/2,0);
There's still code after that but those pieces of code are not involved in my problem
Thanks for watchingscripting problemmathmapgpsFri, 02 Jul 2021 10:21:34 GMTBlizzaceTrack distance travelled using GPS
http://answers.unity.com/questions/1842923/track-distance-travelled-using-gps.html
I have an app (Android and iOS) that shows the User their current location on a map (using Mapbox) with location-based markers. When they go to these locations physically, they unlock content.
This all works great but now I want to add a new functionality: Track the distance they have walked.
As they can start at any marker and visit them in any order, I don't want to calculate 'as the bird flies' but rather, the exact route they took; as this is the real world, they wouldn't necessarily walk in a straight line.
How would I go about tracking how far they have walked? I'm thinking I could use the GPS in some way.
Ideally I would also like to update it regularly so they can see their progress whenever they want.mathdistancelocationtrackinggpsThu, 17 Jun 2021 10:23:08 GMTDJgray3DCalculate collision between 2 rotated boxes without using BoxCollider (MATH)
http://answers.unity.com/questions/1840803/calculate-collision-between-2-rotated-boxes-withou.html
I am developing a 3D grid system for my game so I'll have to calculate box collisions dozens of times per frame. I need to find a way to calculate the collision between 2 boxes given the position, size, and rotation. Adjacent boxes shouldn't detect collision. NOTE: I don't know any advanced math
It would be preferred if you fill in the gaps of the following function:
bool Intersects(Vector3 positionA, Vector3 sizeA, Quaternion rotationA, Vector3 positionB, Vector3 sizeB, Quaternion rotationB)
{
//content...
//returns true if both boxes collide
}
Intersects(new Vector3(0f, 0f, 0f), Vector3.one, Quaternion.Euler(Vector3.zero), new Vector3(1f, 0f, 0f), Vector3.one, Quaternion.Euler(Vector3.zero));
//adjacent boxes should return FALSEphysics3dmathspacevectorsSun, 06 Jun 2021 17:56:54 GMTRaja-Unityhow do you set a float to infinity without using Mathf.Infinity for use in Jobs?
http://answers.unity.com/questions/1840052/how-do-you-set-a-float-to-infinity-without-using-m.html
I am writing code for use in the unity **jobs system with the burst compiler** so ideally `Unity.Mathematics.math` would be used to set the `float` to `infinity` instead of `Mathf.Infinity`. I haven't been able to find a way to set a float to infinity in the mathematics library, however and tried setting it to INFINITY and `1/0` but those did not work.
Is using `Mathf.Infinity` valid in jobs with the burst compiler or is there another way to set a value to infinity that I am just looking over?mathThu, 03 Jun 2021 09:59:15 GMTJatosIs Mathf.Infinity compatable with the burst compiled in Jobs?
http://answers.unity.com/questions/1840090/is-mathfinfinity-compatable-with-the-burst-compile.html
I thought I would get errors using Mathf.Infinity in a burst compiled job but it hasn't thrown any errors yet. I am confused because Mathf.Infinity is technically a static float which normally disables burst and when I try to make my own static variables for use in a job it would throw an error, am I misunderstanding something?
Also, is there an equivalent to Mathf.Infinity in the Unity.Mathematics.math library? I haven't been able to find it which seems weird since it does exist in MathfmathmathfThu, 03 Jun 2021 04:01:03 GMTJatos2.5D Platformer where character moves between points has issues where physics take player off of the line between points.
http://answers.unity.com/questions/1838397/25d-platformer-where-character-moves-between-point.html
Hello all. I'm making a game that operates like a 2.5D platformer in 3D Space. The character is a rigidbody that moves between these way points that are anywhere on the x,y,z axis. The way I have the character move is I apply forces and velocity changes in the direction (The vector 3 of the point they are moving towards). However, if the player is moving towards a point and a wall/platform is in the way, now if they player just continues to run towards that wall, the rigidbody will instead slide the player off to the side of the platforms. Thus, no longer being in 2.5D space and probably falling off the level.
I've tried things like changing the physics material or making velocity 0 if a raycast detects a wall as the player is running towards a wall but that mitigates the problem and if they player sits there long enough running at the wall, they can end up falling off the level.
What might be the better way of doing this is to make sure that the player is always getting back to the nearest point of the invisible line between the 2 points. How would I begin to express this in code? Thanks in advance.collisionphysicsrigidbodymathTue, 25 May 2021 18:53:39 GMTSirKingKrabRotate 3d vector based on local forward
http://answers.unity.com/questions/1838090/rotate-3d-vector-based-on-local-forward.html
Hey all,
I'm trying to rotate a 3d vector [input] so that:
local forward
= (0,0,1) => input is not rotated
= (1,0,0) => input is rotated 90 deg
= (0,0,-1) => input is rotated 180 deg
= (-1,0,0) => input is rotated 270 deg
// movement is on the xz plane
Basically, I've got player input as a vec3 in a top down / twin stick shooter game and i'd like to use to it drive the blend tree animations. However, animations are relative to the direction the player is facing, so the input values need to be rotated to map to the proper animation values. For example if the player is pressing the [move right key] and facing east, i'd like to play the forward animation. If the player is facing south and presses the same [move right key] i'd like to play the strafe to the left animation.
I think https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html is a good start but I couldn't get figure out how to properly apply it here.
How can I achieve this effect? Thanks for any help!vector3mathMon, 24 May 2021 04:59:13 GMTkirbygc00Rotate around to angle with lerp
http://answers.unity.com/questions/1836380/rotate-around-to-angle-with-lerp.html
![alt text][1]
[1]: /storage/temp/180690-problem.png
How to do itmathrotation axisrotatearoundFri, 14 May 2021 18:56:50 GMTgravelpootisHow to calculate correct angles for PID?
http://answers.unity.com/questions/1833890/how-to-calculate-correct-angles-for-pid.html
Hello.
<br><br>
I'm working on flying mechanic for space craft and I use PID to calculate it's movement.<br>
I have a target which I'd like my ship to look to.
So, here is my implementation, most part of it is taken from [this great tutorial about PID][1].<br>
Also, it may be worth it to take a look at [PID implementation for Unity][2]
<br><br>
// Target rotation between ship and its target
Quaternion targetRotation = Quaternion.LookRotation(transform.position - Target.position);
// The "error" between current angle and desired (to look at the target)
float xAngleError = Mathf.DeltaAngle(transform.rotation.eulerAngles.x, targetRotation.eulerAngles.x);
// Calculate correction via PID
float xTorqueCorrection = xAxisPIDController.GetOutput(xAngleError, Time.fixedDeltaTime);
// Apply to rigid body
_rigidbody.AddRelativeTorque(xTorqueCorrection * Vector3.right, ForceMode.Force);
<br>
And how it looks:
<br><br>
![Demonstration of PID][3]
<br>
So, there are a few problems I have, but I think all of them are because of angles calculation (Even tutorial's author mentioned it).
When target is directly above the ship, it starts to spin.
<br><br>
![Problem with angle][4]
<br>
I think it happens because of the way I calculate errors. It works great for all the Z and Y, but not for X.
<br><br>
Please, help me find the correct way to calculate errors for PID.
[1]: https://www.youtube.com/watch?v=roxhVW3KeRY
[2]: https://github.com/Tvtig/UnityPIDController/blob/master/Assets/Scripts/PID.cs
[3]: https://vk.com/doc40928941_593089635?hash=6924d669d3f99f4f53&dl=8bdd11e87200225a59&wnd=1&module=public
[4]: https://vk.com/doc40928941_593089975?hash=be6c875458d037222a&dl=b44a7a902865b1e824&wnd=1&module=publicrotationphysicsmathcalculationeuler anglesSun, 02 May 2021 20:46:49 GMTmishakozlov74How to find centers of inner child of a quad (geometry guy needed)?
http://answers.unity.com/questions/1833033/how-to-find-centers-of-inner-child-of-a-quad-geome.html
The same question on the Unity Forum with readable text - https://forum.unity.com/threads/how-to-find-centers-of-inner-child-of-a-quad-geometry-guy-needed.1100416/
Hi, I have not very big experience in the game development sphere (around 4 years), but I have collided with this problem at least 2 times already. And every time I solved it with the stupidest method. Now I have collided with it 3rd time and I need to solve it in a smart way.
Problem description:
Imagine, that we have a plane (quad or rectangle) [img. 1]. We want to split it into 4 children of the same size. We know all about this plane - its dimensions and center position. So we easily calculated the child's plane size and ready to move on. What we need to do next - is to define where we want to place every child. And this is the task - "how to find child plane position in the smartest (and possibly the fastest way)?"
![alt text][1]
The result we want to achieve
![alt text][2]
[1]: https://forum.unity.com/attachments/square-png.842992/
[2]: https://forum.unity.com/attachments/upload_2021-4-27_20-45-8-png.843013/
All next info was based on the concept that we decide that we want to find centers of that small planes.
Solution 1 - Cavemen calculations
The ugliest way to resolve this task. I used it before when I need to resolve this kind of problem. And it works pretty robustly, like stone, that was taped to the stick by our grandgrandgrandfather. But this solution is ugly. It will produce a tone of bugs. It hard-to-modify solution. And it will be even more complicated for 3D.
The code of the solution
public void Split ()
{
Vector3 nodeBoundsExtents = NodeBounds.extents;
float nodeBoundsExtentsX = nodeBoundsExtents.x;
float nodeBoundsExtentsZ = nodeBoundsExtents.z;
Vector3 childBoundsSize = new Vector3(nodeBoundsExtentsX, 0, nodeBoundsExtentsZ);
Vector3 childBoundExtents = childBoundsSize / 2.0f;
Vector3 nodeCenterPosition = NodeBounds.center;
Vector3[] childPositions =
{
new Vector3(nodeCenterPosition.x, 0, nodeCenterPosition.z) - childBoundExtents,
new Vector3(nodeCenterPosition.x, 0, nodeCenterPosition.z) + childBoundExtents,
new Vector3(nodeCenterPosition.x - childBoundExtents.x, 0, nodeCenterPosition.z + childBoundExtents.z),
new Vector3(nodeCenterPosition.x + childBoundExtents.x, 0, nodeCenterPosition.z - childBoundExtents.z)
};
foreach (Vector3 childPosition in childPositions)
{
CreateChild(childPosition, childBoundsSize);
}
}
private void CreateChild (Vector3 centerOfTheNewChild, Vector3 childBoundsSize)
{
GameObject child = new GameObject();
BoxCollider boxTest = child.AddComponent<BoxCollider>();
boxTest.size = childBoundsSize;
child.transform.position = centerOfTheNewChild;
}
This solution is based on one action - we just get the center of the big plane and shift it with offset with size of the small quad in different directions.
Solution 2 - When you try to impress your crush with your math skills
This solution is a bit better than the first, but it has a few cons:
- It doesn't intuitive and it not
stupid and simple
- It can produce strange results when
you will mess with the mirror vector.
- It will become completely messy in
3D.
The code of the solution
public void Split ()
{
Vector3 nodeBoundsExtents = NodeBounds.extents;
float nodeBoundsExtentsX = nodeBoundsExtents.x;
float nodeBoundsExtentsZ = nodeBoundsExtents.z;
Vector3 childBoundsSize = new Vector3(nodeBoundsExtentsX, 0, nodeBoundsExtentsZ);
Vector3 childBoundExtents = childBoundsSize / 2.0f;
Vector3 nodeCenterPosition = NodeBounds.center;
Vector3 firstQuadCenter = new Vector3(nodeCenterPosition.x, 0, nodeCenterPosition.z) - childBoundExtents;
Vector3[] childPositions =
{
firstQuadCenter,
firstQuadCenter * -1,
Vector3.Reflect(firstQuadCenter, Vector3.right),
Vector3.Reflect(firstQuadCenter, Vector3.forward)
};
foreach (Vector3 childPosition in childPositions)
{
CreateChild(childPosition, childBoundsSize);
}
}
private void CreateChild (Vector3 centerOfTheNewChild, Vector3 childBoundsSize)
{
GameObject child = new GameObject();
BoxCollider boxTest = child.AddComponent<BoxCollider>();
boxTest.size = childBoundsSize;
child.transform.position = centerOfTheNewChild;
}
Looks smart, doesn't it? We used magical Vector3.Reflect() and g̶e̶t̶ ̶b̶u̶n̶n̶y̶ ̶o̶u̶t̶ ̶f̶r̶o̶m̶ ̶a̶ ̶h̶a̶t̶ made our code a bit smaller. You can show this code to your crash and she/he will probably let you hug her/him (joke, programmers with girlfriend - it's a myth).
But, what if I want to mirror my start cube by diagonal, but opposite to firstQuadCenter * -1? And I'm sure this will look messy for 3D. However, this code is still pretty robust for 2D. I think this solution is better than the first one, but not the "best practice".
Solution 3 - Dizzy rotation
This solution came to me when I remembered my math lessons about sines and cosines. We can rotate that stuff from 0 to 360 degrees and functions will change their sign.
The code of the solution
public void Split ()
{
Vector3 nodeBoundsExtents = NodeBounds.extents;
float nodeBoundsExtentsX = nodeBoundsExtents.x;
float nodeBoundsExtentsZ = nodeBoundsExtents.z;
Vector3 childBoundsSize = new Vector3(nodeBoundsExtentsX, 0, nodeBoundsExtentsZ);
Vector3 childBoundExtents = childBoundsSize / 2.0f;
Vector3 nodeCenterPosition = NodeBounds.center;
Vector3 firstQuadCenter = new Vector3(nodeCenterPosition.x, 0, nodeCenterPosition.z) - childBoundExtents;
float[] rotateAngles =
{
0.0f,
90.0f,
180.0f,
270.0f
};
Vector3 rotationDirection = firstQuadCenter - nodeCenterPosition;
foreach (float rotateAngle in rotateAngles)
{
Vector3 rotatedDirection = Quaternion.Euler(new Vector3(0.0f, rotateAngle, 0.0f)) * rotationDirection;
CreateChild(rotatedDirection + nodeCenterPosition, childBoundsSize);
}
}
private void CreateChild (Vector3 centerOfTheNewChild, Vector3 childBoundsSize)
{
GameObject child = new GameObject();
BoxCollider boxTest = child.AddComponent<BoxCollider>();
boxTest.size = childBoundsSize;
child.transform.position = centerOfTheNewChild;
}
Smart? - Maybe. Simple? - not really. I believe this is the most uncomfortable and complicated-to-understand solution. Without any comment or image, it is hard to understand why we need to rotate something and where we do this rotation. I don't want to have this code, not in this form at least.
The algorithm of this solution is quite simple - we just rotate the first small quad's center around the big quad's center clockwise (also we can do counterclockwise move). We rotate it with step 90. And here we can find a big disadvantage of this solution - it can be used effectively only for quad, not for the rectangle (every rectangle will have other rotation step value).
Conclusion
So, that's all from my side. I have no more solutions and can't imagine anything new for now. I'm pretty sure that there is a formula or two, that will resolve this geometry problem with 2 lines of robust code.
I will be very happy if you will share your solutions or comments for my and we will find the best solution sooner or later. Or a smart guy will glance on this thread and just say "But we already have the function GameObject.SplitQuadOn4Parts(), check the documentation".c#mathalgorithmgeometryWed, 28 Apr 2021 22:02:26 GMTMagicianArtemka