Questions in topic: "math"
http://answers.unity.com/questions/topics/single/160.html
The latest questions for the topic "math"Is there such a thing as Unity Algebra?
http://answers.unity.com/questions/1665020/is-there-such-a-thing-as-unity-algebra.html
I have seen some questions about Linear Algebra with the importance indicating the abstract math. What I am interested in learning from Unity is the abstract of the Unity Algebra. For example, when writing equations using math abstract symbols describing the GameObject's Transform and its properties, the position, the rotation and the scale, what symbols do the Unity Team uses when writing out such symbolic equations. How does the symbols reflect the reference frames between local and global? The Unity Manuel and the Unity Scripting does not cover this topic at all... Big question, when writing an article about the Unity Game Engine, I would think they would want consistency describing their math. Please update your Manuels with an advanced section showing the abstract symbolic math related to you vectors and matrices and how they relate to each other...
I like to continue this conversation in the forms but again I do not see where to go to do this... If you want people to write professional articles covering Unity with a consistent symbolic algebra then allow the Unity Team to gives us the Unity Algebra that they use. What I mean by Algebra is a text (textbook) showing the math operations T subscript L for local-transform and T subscript G for global-transform, etc...
Seriously, I really need the Unity Algebra when writing articles, Unity's User can lookup the algebra in Unity's Algebra Textbook...
Thank YoutransformquaternionmathvectormatrixThu, 12 Sep 2019 19:05:15 GMTUniteMageSame movement speed on server, despite send rate from client
http://answers.unity.com/questions/1664937/same-movement-speed-on-server-despite-send-rate-fr.html
On a networked game, the game clients send their desired positions via fixed send rate, example:
while(true) {
SendMyPos(posX);
Thread.Sleep(30);
}
On server-side, I calculate the next player position, applying a speed (stored on server) value to it:
player.position.x += x * speed_StoredOnServer;
The server sends the player positions with a fixed send rate too, but that's not a problem.
**The problem:**
The player's actual speed is affected by the client-to-server send rate. The higher the client-to-server send rate is, the faster the player will move on the server side.
My goal is to make the speed on server-side independent from the client-to-server send rate. I'm sure it can be achieved with a simple formula, but so far I have no solution.movementnetworkingmathserversideThu, 12 Sep 2019 13:33:22 GMTNetkicksDevCould anyone help me with a bit of math for an XP system?
http://answers.unity.com/questions/1662879/could-anyone-help-me-with-a-bit-of-math-for-an-xp.html
If my required XP to level up is 95/100 and I award 10xp, what's the best way to check what's leftover and put it in a variable that I can add after I level up?
Because at the moment if 95/100 and award 10, it will level up and go to 0 losing out on the 5.
Sorry if it's a bit of a vague/mundane question, I struggle with maths.
public float currentXP;
public float RequiredXP;
//If current is 95 and required is 100
public void GiveXp(float xp)
{
//check if the given xp is higher than the required xp
//And add the leftover into a variable so i can add on after
//To the levelup function
}
if I remember anything it may include the modulo % but I really struggle with math.
ThanksmathxpTue, 03 Sep 2019 23:02:46 GMTDivinitize1How to calculate the 3D vector perpendicular to a polygon surface in a specific direction
http://answers.unity.com/questions/1662376/how-to-calculate-the-3d-vector-perpendicular-to-a.html
I'm creating an asteroid mining game in Unity 3D, where "down" is the center of the planet you are on (So I am mostly using local rotations when dealing with vectors). I have a working physics-based character controller, but it has problems dealing with slopes. This is because when I add a force to the character, currently it pushes along the player's forward vector (see picture). What I want to do is calculate the vector that is parallel to this terrain surface, but in the direction that the player is facing (so that the player can move up the slope).
I originally thought that i could just find the vector perpendicular to the normal, but then how do I know which direction it will be in. Also complicating matters is the fact that the player could be oriented in any way in relation to the global x, y, and z.
Either way, I have the surface normals of the terrain, I have all of the player's directional vectors, but I just can't figure out how to put them all together. I can upload code or screenshots of the editor if necessary. Thanks.
![ms paint drawing][1]
[1]: /storage/temp/145577-perpvector.pngvector3mathnormalsSun, 01 Sep 2019 18:26:59 GMTdaddylongleggsHow do i place objects in a parabolic shape?
http://answers.unity.com/questions/1662143/how-do-i-place-objects-in-a-parabolic-shapehow-do.html
for (int w = 0; w < width; w++)
{
int height = 10;
for (int h = 0; h < height; h++)
{
Instantiate(dirt, new Vector3(w, h), Quaternion.identity);
}
}
creates a 10x10 square as expected:
![alt text][1]
for (int w = 0; w < width; w++)
{
int height = w;
for (int h = 0; h < height; h++)
{
Instantiate(dirt, new Vector3(w, h), Quaternion.identity);
}
}
creates a linear shape because its basically y = x:
![alt text][2]
so how do i create a y = -x^2 like shape?
this formula doesn't work btw.
[1]: /storage/temp/145529-sharedscreenshot.jpg
[2]: /storage/temp/145530-sharedscreenshot1.jpgmathSat, 31 Aug 2019 16:50:23 GMTMakkerFelixWrong implementation of Pi in Mathf Library
http://answers.unity.com/questions/1659650/wrong-implementation-of-pi-in-mathf-libraryvalue-o.html
I just noticed that the value of Mathf.PI seems to be wrongly implemented. The definition reads:
public const float PI = 3.14159274F;
Obviously the last two digits should be 65. Is this a bug?mathscript errorlibraryThu, 22 Aug 2019 09:49:23 GMTEntropicalHow to import an expression evaluator into unity?
http://answers.unity.com/questions/1659293/how-to-import-an-expression-evaluator-into-unity.html
Hi,
All i need is for my script to be able to read a string as a mathematical expression, and solve it. It doesn't need to understand any complicated math (variables or formulas). Just pure basic algebra. Unity's version only works in the editor but doesn't work when i build. I've tried importing NCalc and Expressive-master, but i can't get them to work (never tried to import custom C#, .NET libraries with unity). Any help/tips would be appreciated.c#networkingmathlibraryWed, 21 Aug 2019 06:12:43 GMTbenjiHiltonDotted line bouncing on Unity
http://answers.unity.com/questions/1658566/dotted-line-bouncing-on-unity.html
I am trying to replicate a shooter from any bubble shooter. Dotted line that the bubble will follow.
What I am trying to do is, create a dotted line that bounces (reflects) when getting close the camera limits (camera's limits are the image's limits). Also, to stop creating more dots when hit with a Bubble (blue dot).
The line so far bounces, but not correctly (see corners). Also, it does not stop when hit with a Bubble (blue dot).
private void DrawPoints() {
bool hasReversed = false;
bool reversedLeft = false;
var leftEdge = mainCamera.ScreenToWorldPoint(new Vector3(0, 0, 0));
var rightEdge = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0));
var normalDir = shootDir.normalized;
int count = 0;
for (var i = 0; i < dots.Count; i++) {
var dot = dots[i];
dot.GetComponent<SpriteRenderer>().color = color;
var newPos = new Vector2(normalDir.x, normalDir.y) * i * DotGap;
if (hasReversed) {
newPos.x += reversedLeft ? (-rightEdge.x + Constants.BubbleRadius/2) * 2 * count : (rightEdge.x - Constants.BubbleRadius/2) * 2 * count;
//newPos.x += reversedLeft ? (-rightEdge.x + Constants.BubbleRadius) * 2 : (rightEdge.x - Constants.BubbleRadius) * 2;
}
//newPos += normalDir * delta;
dot.transform.localPosition = newPos;
RaycastHit2D hit = Physics2D.Raycast(newPos, shootDir);
if (hit.collider != null) {
float distance = Vector2.Distance(hit.transform.position, newPos);
if (distance < Constants.WhiteCircleRadius + Constants.BubbleRadius) {
dot.SetActive(false);
Debug.Log("Found!: " + distance + " " + hit.collider.name);
break;
} else {
dot.SetActive(true);
}
}
if (dot.transform.localPosition.x <= leftEdge.x + Constants.BubbleRadius) {
hasReversed = true;
reversedLeft = true;
normalDir = Vector2.Reflect(normalDir, Vector2.left);
count++;
}
else if (dot.transform.localPosition.x >= rightEdge.x - Constants.BubbleRadius) {
hasReversed = true;
reversedLeft = false;
normalDir = Vector2.Reflect(normalDir, Vector2.right);
count++;
}
}
}
The image as follows: The red dot is the pivot (start of the dotted line). The blue dot, is a bubble.
![alt text][1]
[1]: /storage/temp/144788-screen-shot-2019-08-15-at-120420-pm.pngmathreflectionvector2raycasthit2dSun, 18 Aug 2019 07:21:04 GMTAlexhatorCircle-line Intersection Points
http://answers.unity.com/questions/1658184/circle-line-intersection-points.html
Hi. As you can see from the image i have a line and start/end points of that line. how can i find the 2 points where line intersects with the circle.
i've found a post on a website and a video tutorial but i can't implement it in Unity because i am noob. can someone help please?
[website post](https://www.analyzemath.com/CircleEq/circle_line_intersection.html),
[video tutorial](https://www.youtube.com/watch?v=OuAhkinZVsU)
![alt text][1]
[1]: /storage/temp/144693-img.pngmathlinecirclegeometryintersectionFri, 16 Aug 2019 13:01:23 GMTFerrissi have a line that goes through a circle. how can i find intersection points?
http://answers.unity.com/questions/1657918/i-have-a-line-that-goes-through-a-circle-how-can-i.html
Hi. I have an point on edge of a circle and a direction where that point facing. When i draw a ray from that point i want that line to end at other edge of circle but i don't know how can i calculate that point because that line does not go from center(if it would then length of line would be same as diameter of circle). if i can find the other point then i can calculate the length of it by using chord of circle formula which is what i actually need.
![alt text][1]
[1]: /storage/temp/144629-imgg.pngmathgeometrycirclesThu, 15 Aug 2019 12:05:30 GMTFerrissCalculating jump while rotating around pivot
http://answers.unity.com/questions/1656493/calculating-jump-while-rotating-around-pivot.html
i want make the player be able to jump inside a cylinder while rotating around a pivot point![alt text][1]
this is what it looks like
![alt text][2]
this is what i want to achieve.
what i thought i could do was take the local up direction as its pointing directly away from pivot and taking the inverse value and doing something with that but i just cant seem to get it to work. i was able to test this out as well in the editor by changing the coordinate space to local and it works. but i just cant wrack brain around how im supposed to do this since i also want the player be able to rotate around while mid air jumping as well.
if anyone has any clue on how to do this it would help me out a lot
[1]: /storage/temp/144395-untitled-1-01.jpg
[2]: /storage/temp/144396-untitled-1-02.jpgscripting problemlerpmathjumpingpivot-pointSat, 10 Aug 2019 17:48:24 GMTsujitha304How to control horizontal movement while making Sine wave pattern?
http://answers.unity.com/questions/1656041/how-to-control-horizontal-movement-while-making-si.html
Hi,
For a very small personal project in AR i'm trying to control the movement of a sphere(Only Horizontally) while it's making a Sinewave pattern.
For example:
Sphere is going from point A to point B with a sinewave pattern.
I press the right button (on the touchscreen of the phone)
The spere moves to the right but it maintains it's wave without chaging magnitude, frequency, etc.
I've tried with a Sinewave script:
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour {
public float MoveSpeed = 5.0f;
public float frequency = 20.0f; // Speed of sine movement
public float magnitude = 0.5f; // Size of sine movement
private Vector3 axis;
private Vector3 pos;
void Start () {
pos = transform.position;
//DestroyObject(gameObject, 1.0f);
axis = transform.right; // May or may not be the axis you want
}
void Update () {
pos += transform.up * Time.deltaTime * MoveSpeed;
transform.position = pos + axis * Mathf.Sin (Time.time * frequency) * magnitude;
}
}
And then adding a movement script to the camera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
//variables
public float moveSpeed = 300;
public GameObject character;
private Rigidbody characterBody;
private float ScreenWidth;
// Use this for initialization
void Start () {
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
int i = 0;
//loop over every touch found
while (i < Input.touchCount) {
if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
//move right
RunCharacter (1.0f);
}
if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
//move left
RunCharacter (-1.0f);
}
++i;
}
}
void FixedUpdate(){
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput){
//move player
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}
But they override each other and they don't work simultaneously.
Anyone got an idea?mathplayer movementSat, 10 Aug 2019 07:07:39 GMTunity_0yC6vhmB0kheggGetting the distance in a known direction
http://answers.unity.com/questions/1656240/getting-the-distance-in-a-known-direction.html
Hi, I would like to calculate the distance between my Player and a Wall using a known direction (-Transform.left in my example).
![Drawing of how distance should be calculated][1]
Using Vector2.Distance doesn't work, as it only gives the absolute distance. I could use a line of raycasts to try to hit the Player and get the distance that way but that wouldn't be really accurate enough.
I hope someone can help me thx.
[1]: /storage/temp/144363-annotation-2019-08-09-231920.pngc#directiondistancemath2d-physicsFri, 09 Aug 2019 21:57:30 GMTGaweringoHow to make a circle with three known points
http://answers.unity.com/questions/1655538/how-to-make-a-circle-with-three-known-points.html
I want to make a throwable weapon that will arc towards its target.
Right now the best way I can think of is to make a circle with three points and have the object travel along the minor arc
A = player position
B = target position
C = a point that's perpendicular to the AB line and offset by the player
I can't figure out how to get the point of the center of the circle (point D)
If it changes the math / code, I need this to work in 3D so the player can aim their arc up or down too
edit: (If 3d makes everything much more complex I think I thought of a way to make 2d work for me)
Thanks for any help, I've been stuck for awhile on this
![alt text][1]
Not the prettiest picture but I hope it gets the point across
[1]: /storage/temp/144239-bandicam-2019-08-07-20-18-08-299.jpg
Answered:
My result is in a commentmathcirclecurvearcThu, 08 Aug 2019 01:31:57 GMTNWinClosest point on multiple lines?
http://answers.unity.com/questions/1654911/closest-point-on-multiple-lines.html
So there are several answers for "find the closest point on a line", but I'm having a time extrapolating that math to multiple lines. How would I find the closest point on any line from say, an array of lines? (Especially if that array might be dozens or even hundreds of lines)
Specifically what I'm trying to do is place objects alongside one of any number of road sections. Roads are interlocking, and each has a curb section that the player can place objects along. They could be hovering over any number of roads, along either side of the sidewalk - how do I find the correct closest one among all that noise? Thank you!vector3distancemathvector2pointTue, 06 Aug 2019 04:29:45 GMTnyongeAdvanced Progressive difficulty monster spawner
http://answers.unity.com/questions/1654364/advanced-progressive-difficulty-monster-spawner.html
So i am in the middle of creating an equation that will become the basis of my Monster Spawner.
The goal is to increase the difficulty over time for the player.
My approach goes as follows:
i have one struct within a struct.
The first struct determines the Tier that the enemy is in and the second struct the tier within the tier that the enemy is in.
There is a currentTierDifficulty variable which is based on the TimeElapsed. The current tiercap starts at 1 and finishes at whatever number of tiers there are. (realistically around 8 or less). The currenttierdifficulty increases around 0.002 every second which should make it reach tier 8 in around an hour.
The CurrenttTierCap is the currentTierDifficulty rounded to the nearest integer.
any tier below the the currentcap is available to be chosen.
i want each tier to be weighted.
for example:
CurrentTierDifficulty = 3.6
currentTierCap = 4
tier 1 <=== (0.4)
tier 2 <=== (0.2)
tier 3 <=== (0.15)
tier 4 <=== (0.05)
tier 5 not available because lower than currenttiercap
tier 6 not available because lower than currenttiercap
tier 7 not available because lower than currenttiercap
etc
but i also want the weight to slowly shift towards the end of the tier list so that toward the end of the one hour, you will only have tier 5, 6 and 7 monsters spawning.
so whenever i decide to spawn an enemy, a function checks the two struct and randomly selects a monster based on all of this information
i tried to make it as clear as i possibly can.
i have added a picture of what i have so far and where i am stuck.![alt text][1]
[Serializable]
public struct EnemyTier
{
public float BaseWeight;
[Serializable]
public struct NamedEnemy
{
public string name;
public int BaseHealth;
public float BaseDamage;
public float BaseSpeed;
public GameObject EnemyPrefab;
}
public NamedEnemy[] Enemie;
}
public EnemyTier[] Enemies;
int TotalNumberofTiers;
public int TimeinMinutes = 400;
public float TierDifficulty = 1;
public float TierIncreasePer10Seconds;//default is 0.002 per sec = 7.2 in one hour
private void Start()
{
TotalNumberofTiers = Enemies.Count();
TierIncreasePer10Seconds = TotalNumberofTiers / TimeinMinutes;
InvokeRepeating("DifficultyAdjustment", 10,10);
}
/// <summary>
/// selects the appropriate enemy from the structs
/// </summary>
public GameObject EnemySelection()
{
int PrecentageChance = 100 / TotalNumberofTiers;
int CurrentTierCap = Mathf.RoundToInt(TierDifficulty);c#unity 5mathstructSat, 03 Aug 2019 18:16:15 GMTPrimeSoulCap Slerp rotation if above certain angle
http://answers.unity.com/questions/1650309/cap-slerp-rotation-if-above-certain-angle.html
I am trying to cap the angle of rotation of a Slerp if it goes above 1 degree to a quaternion which Euler angle magnitude would be 1 degree and in the same direction as the Slerp function.
This is my current attempt.
void Slerp()
{
var localRotation = rcsSpace.localRotation;
var newRot = Quaternion.SlerpUnclamped(localRotation, plannedRot, t).normalized;
var rotVector = newRot * Quaternion.Inverse(localRotation);
if (Quaternion.Angle(localRotation, newRot) < 1f)
{
rcsSpace.localRotation = newRot;
}
else
{
rcsSpace.localRotation = rotVector * localRotation;
}
}
I was thinking that I could get the magnitude of the rotVector and divide it by itself however this does not seem possible with Quaternions.
Many Thanks.rotationmathquaternionsSat, 20 Jul 2019 18:20:39 GMTAureliusIIGet value -1 to 1 from direction between 2 points
http://answers.unity.com/questions/1648223/get-value-1-to-1-from-direction-between-2-points.html
So, this is somewhat of a loaded question and I will try to do my best to explain it.
I am creating a vehicle AI system, and the vehicle has a Steer(x) function. X ranges from -1(steer left) to 1(steer right).
I'm trying to find the value that I need to pass to that function to steer my vehicle accordingly to a target, in this case the next checkpoint.
An example: Imagine a vehicle to the right of a checkpoint, this function should return something like -0.2 to steer the vehicle back towards the checkpoint.
This is what i've tried:
Vector3 relativePos = path.corners[0] - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(relativePos);
float y = transform.eulerAngles.y;
float DeltaAngle = Mathf.DeltaAngle(y, targetRotation.eulerAngles.y);
Debug.Log(DeltaAngle / 360f);
and
float dot = Vector3.Dot(transform.forward.normalized, (_Target.position - transform.position).normalized);
However it doesn't produce the correct steering value.
Any help would be appreciated.c#aimathSat, 13 Jul 2019 08:21:03 GMTCyprasA graph to render sine wave with custom resolution
http://answers.unity.com/questions/1648090/a-graph-to-render-sine-wave-with-custom-resolution.html
Hello. I try to create a sine wave radar signal visualization using a line renderer component and it works well. It has it's own:
- resolution (points per unit, e.g. 5
points per unit);
- step (distance between each
point);
- total points count (depends on resolution and distance);
- max spread distance (max distance
for the whole wave);
- current spread distance (equals
the distance from the ray's origin
to hit point when the ray reach
and hit any tagged object).
Now I have a problem with calculating the perfect length of the whole sine wave when the ray hit an object). It is always bigger than it should be. Guys, help me please... I spent about 6 hours to try to fix that issue and I had no success. I'm done. Here's my code:
using UnityEngine;
namespace RLS
{
[RequireComponent(typeof(LineRenderer))]
public class Wave : MonoBehaviour
{
LineRenderer m_LineRenderer;
[Range(1, 255)] public float maxSpreadLength = 10;
[Range(1, 255)] public float curSpreadLength;
[Range(1, 255)] public byte resolution = 5;
public float step;
public int pointsAmount;
public float a;
public float w;
public string dispersionTag = "Dispersion";
Vector3 origin;
Vector3 direction;
RaycastHit hitInfo;
void Start()
{
m_LineRenderer = GetComponent<LineRenderer>();
}
void FixedUpdate()
{
DrawWave();
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, direction * curSpreadLength);
Gizmos.color = Color.blue;
Gizmos.DrawSphere(hitInfo.point, 1.0f);
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, hitInfo.point);
}
public void DrawWave()
{
origin = transform.position;
direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(origin, direction, out hitInfo, maxSpreadLength) && hitInfo.transform.gameObject.tag == dispersionTag)
{
if (hitInfo.distance <= maxSpreadLength)
{
Debug.Log("D <= MAX!");
curSpreadLength = hitInfo.distance;
}
}
else
{
curSpreadLength = maxSpreadLength;
}
pointsAmount = resolution * (int)curSpreadLength;
step = curSpreadLength / (float)pointsAmount;
m_LineRenderer.positionCount = pointsAmount;
for (int i = 1; i < pointsAmount; i++)
{
float x = (float)i * step;
m_LineRenderer.SetPosition(i, new Vector3(a * Mathf.Sin(x * w), 0.0f, x));
}
}
}
}c#scripting problemmathsine-waveFri, 12 Jul 2019 17:38:25 GMTfl1ckjeConvert World and LocalPositions of different objects
http://answers.unity.com/questions/1646194/convert-world-and-localpositions-of-different-obje.html
In order for a lean ADS i want to move the weapon IK Target relative to the camera. Unfortunately caused of other dependencies i am not able to change the hierarchy .
----------
**Current State** (Only changing Rotation no camera transition):
https://www.youtube.com/watch?v=WGWpjmjsB58
----------
At the end i want to Vector3.Lerp the camera left/right --> Leaning.
So does anyone know how i can convert the world position of the camera into the local position of the targets coordinate system?
Sry, could upload a picture of the hiearchy somehow.mathSat, 06 Jul 2019 12:04:34 GMTMichael_RNormalizing Animation Clip to One Second
http://answers.unity.com/questions/1646152/normalizing-animation-clip-to-one-second.html
Hi all, what I'm trying to do is set a variable for "AttackDuration". This value would be the time, in seconds, it would take to complete the attack animation.
To do that, I figured I would have to normalize the clip lengths to 1 second, that way I would have a baseline.
To do that, I just used a simple:
timeDeltaPercentage = 1 / clipTime;
This gives me the difference in the clipTime to one second. i.e. a clip that was 1.5 seconds would give a percentage of .666667...
I then take that percentage and do the following calculation:
animatorSpeed = (1+timeDeltaPercentage) / targetAttackDuration;
This seems to get me almost all the way there but the numbers are off by around 10%.
Any ideas what I could be doing wrong?animatormathSat, 06 Jul 2019 07:25:58 GMTs0lt4rHow can I get the Time taken for the 2 moving objects to touch each other
http://answers.unity.com/questions/1645940/how-can-i-get-the-time-taken-for-the-2-moving-obje.html
Hello, I'm new in Unity as well as a beginner at Programming and Making Games
I want to know How Can I calculate the time taken and make a "Count Down" for the 2 objects moving in the same Direction but with different speed to touch each other.script.timedistancemathgameobjectsFri, 05 Jul 2019 09:16:07 GMTaquaphoenix41Calculating endpoints of directional vector
http://answers.unity.com/questions/1644797/calculating-endpoints-of-directional-vector.html
I have the feeling the solution is horribly obvious, but I'm having trouble understanding a bit of vector math: if I want a vector representing the distance between two points, I do something like this:
Vector3 origin;
Vector3 destination;
Vector3 direction = (destination - origin).normalized * Vector3.distance(origin, destination);
So here's where I'm confused: if someone hands me *direction* without any of the accompanying values, how would I calculate *origin* and *destination*? Would *origin* simply be *direction.normalized*?vector3mathMon, 01 Jul 2019 08:59:07 GMTSendatsu_YoshimitsuCalculate offsets correct?
http://answers.unity.com/questions/1643282/calculate-offsets-correct.html
Hello,
----------
i want to a child object (weapon) to have the same position as another object (camera -->no child) by changing the (local-)Position from the parent object (hand palm) of the child
----------
Other explanatation:
(i want to calculate the position of an parent object (hand palm) so that a child object (weapon) has the same position like another object (Camera))mathoffsetinversetransformpointMon, 24 Jun 2019 20:34:27 GMTMichael_RWhy is unity making basic math mistakes (or c#, I don´t know)?
http://answers.unity.com/questions/1642420/why-is-unity-making-basic-math-mistakes-or-c-i-don.html
Hi people, it´s just that I´ve been having a weird bug were an object should return to its original Scale but it doesn´t and bad things happen. The localScale.x is meant to be 1, but instead it gives me 0.99999999 and stuff like that.
Even though the current x and original are the same and we are dividing one by the other, the result is not 1:
Debug.Log("currentX: " + currentX + " original: " + originalObjectSize.x + " localScale: " + currentX / originalObjectSize.x);
//which shows
currentX: 1.608788 original: 1.608788 localScale: 0.9999999
This is not the only time that has happened though. First was with a simple operation as well were I subtracted a sum (x -= bothNumbers) instead of x - firstNumber - secondNumber. Mathematically speaking, they should be the same, but the results were slightly different (about 0.0000002).
I know I could solve this by coding without relaying in specific numbers like I am, but it´s hard and it still shouldn´t happen. When the number becomes bigger is easy to just clamp the value, because I know is wrong, but when is a little bit smaller, it´s difficult to know if it´s an error or if that is really the wanted scale.bugmathFri, 21 Jun 2019 01:28:23 GMTFeref2How to rotate a flat plane towards a point without changing it's orientation
http://answers.unity.com/questions/1642305/how-to-rotate-a-flat-plane-towards-a-point-without.html
I feel like the solution is probably very simple, but getting caught up and i think I'm making it too complex.
If there is a flat square and the surface normal is pointing straight up, how can i rotate it so that normal points towards a point in space without it rotating around the normal vector axis?mathThu, 20 Jun 2019 15:55:13 GMTEdBoonHow would you convert circular joystick input to a square overlay?
http://answers.unity.com/questions/1642093/how-would-you-convert-circular-joystick-input-to-a.html
I'm having an issue converting joystick input to match a square screen. If you directly translate input to the screen, you will get an oval, what I want is a dynamic equation or method for also filling in the corners. I've attempted to go about this several ways and was wondering if anyone has encountered this before. joystick input is debugged, I have the correct values from **joystick.value**.
// Perfect Oval matching rectangular screen
public void DirectTranslation()
{
// Input Extremes: (1,0) (0.7, 0.7) (0, 1) (-0.7, 0.7) (-1,0) (-0.7, -0.7) (0,-1) (0.7, -0.7)
float x = joystick.HorizontalInput;
float y = joystick.VerticalInput;
float xPos = x * Screen.width / 2;
float yPos = y * Screen.height / 2;
reticle.rectTransform.anchoredPosition = new Vector2(xPos, yPos);
}
This was my first attempt to make up for the lost space when in a corner, but ended up with a cross cutout. It perfectly reaches the corners, but skips over any input value from -0.3 to 0.3 (I understand why, but could not get it to be a perfect fix):
// Perfect to the corners, but a cross of null space when x || y are < 0.3
public void Attempt1Fix()
{
float x = joystick.HorizontalInput;
float y = joystick.VerticalInput;
float inputMagnitude = Mathf.Abs(x) + Mathf.Abs(y);
float xRemainder = 0;
float yRemainder = 0;
xRemainder = 1 - Mathf.Abs(x);
xRemainder = Mathf.Clamp(xRemainder, 0, 0.3f);
yRemainder = 1 - Mathf.Abs(y);
yRemainder = Mathf.Clamp(yRemainder, 0, 0.3f);
float xPos = x * Screen.width / 2;
float yPos = y * Screen.height / 2;
float xExtenstion = xRemainder * (Screen.width / 2);
float yExtenstion = yRemainder * (Screen.height / 2);
// Q1: Top Right
if (x > 0 && y > 0) reticle.rectTransform.anchoredPosition = new Vector2(xPos + xExtenstion, yPos + yExtenstion);
// Q2: Top Left
if (x < 0 && y > 0) reticle.rectTransform.anchoredPosition = new Vector2(xPos - xExtenstion, yPos + yExtenstion);
// Q3: Bottom Left
if (x < 0 && y < 0) reticle.rectTransform.anchoredPosition = new Vector2(xPos - xExtenstion, yPos - yExtenstion);
// Q4: Bottom Right
if (x > 0 && y < 0) reticle.rectTransform.anchoredPosition = new Vector2(xPos + xExtenstion, yPos - yExtenstion);
}
So now I started searching for a solution, and I came across this https://stackoverflow.com/questions/13211595/how-can-i-convert-coordinates-on-a-circle-to-coordinates-on-a-square which seems to be a perfect solution my issue. I attempted to translate the mathematics equation to C# code, but it returns some NAN values in certain joystick positions:
// NAN values in some cases
public void Attemp2Fix()
{
float x = joystick.HorizontalInput;
float y = joystick.VerticalInput;
// Equation found at URL in question
// x = ½ √(2 + u² -v² +2u√2 ) - ½ √(2 + u² -v² -2u√2 )
// y = ½ √(2 - u² +v² +2v√2 ) - ½ √(2 - u² +v² -2v√2 )
// Attemp to recreate equation
float xCircle = x * Screen.width / 2;
float yCircle = y * Screen.height / 2;
float xSquare = 0.5f * Mathf.Sqrt(2 + (xCircle * xCircle) - (yCircle * yCircle) + 2 * xCircle * Mathf.Sqrt(2)) - 0.5f * Mathf.Sqrt(2 + (xCircle * xCircle) - (yCircle * yCircle) - 2 * xCircle * Mathf.Sqrt(2));
float ySquare = 0.5f * Mathf.Sqrt(2 - (xCircle * xCircle) + (yCircle * yCircle) + 2 * xCircle * Mathf.Sqrt(2)) - 0.5f * Mathf.Sqrt(2 - (xCircle * xCircle) + (yCircle * yCircle) - 2 * xCircle * Mathf.Sqrt(2));
// Then apply math to reticle position
reticle.rectTransform.anchoredPosition = new Vector2(xSquare, ySquare);
}inputmathjoystickcirclesquareThu, 20 Jun 2019 02:36:52 GMTBradyIrvHow to properly make an object follow the edge of another object?
http://answers.unity.com/questions/1641760/how-to-properly-make-an-object-follow-the-edge-of.html
I want to have a cover system which works so that if the player is near a object big enough and presses the crouch key he hides behind that object basically meaning he is in a crouch animation and can move along it with A and D keys to side to side ([Picture][1]), I made this script but with this the speed variable for the movement while crouched doesn't seem to be taken into account, the thing causing it is the `transform.position = coverPos;` line and I can't find any other way to make the player "snap" to the edge of the other object so any help? The raycasting/cover "snapping" code:
if (Physics.Raycast(coverBottom.position, coverBottom.TransformDirection(Vector3.forward), out hitB, 1.5f, layerMask))
{
coverPosition = hitB.point + hitB.normal * 0.3f;
coverPosition.y = 0f;
if (inCover)
{
Vector3 lastNormal = Vector3.zero;
Vector3 coverPos = new Vector3(coverPosition.x, transform.position.y, coverPosition.z);
transform.position = coverPos;
transform.forward = -hitB.normal;
}
}
The player movement code: (There's lot more of course this is just that one part of it)
public float walkSpeed = 2;
public float runSpeed = 4;
public float crouchSpeed = 0.5f;
public float animationWalkSpeed = 1;
public float animationRunSpeed = 3;
public float animationCrouchSpeed = 0.5f;
else if (!inputController.Run)
{
if (inputController.Cover || inCover)
{
crouch = true;
playerAnimator.SetFloat("speed", animationCurrentSpeed);
decreaser = runSpeed;
decreaser = Mathf.Clamp01(Time.time - secondsTillMaxSpeed);
currentSpeed = Mathf.Lerp(walkSpeed, crouchSpeed, decreaser);
animationCurrentSpeed = Mathf.Lerp(animationWalkSpeed, animationCrouchSpeed, decreaser);
float yStore = moveDirection.y;
if (inCover && h > 0)
{
moveDirection = transform.right * currentSpeed * Time.deltaTime;
}
else if (inCover && h < 0)
moveDirection = -transform.right * currentSpeed * Time.deltaTime;
else if (!inCover && h != 0)
moveDirection = transform.forward * currentSpeed * Time.deltaTime;
moveDirection.y = yStore;
characterController.Move(moveDirection * Time.deltaTime);
}
}
[1]: https://imgur.com/a/Jmbh45kmovementtransformpositionvector3mathTue, 18 Jun 2019 22:13:21 GMTno00obIssues 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 GMTU3DPIs there a moveTowards for float3?
http://answers.unity.com/questions/1639488/is-there-a-movetowards-for-float3.html
There is Vector3.MoveTowards(...), Is there something similar in new Mathematics? All I see is math.lerp(..).
Thanks!mathMon, 10 Jun 2019 18:08:45 GMTAutoRotate