Questions in topic: "calculations"
http://answers.unity.com/questions/topics/single/485371.html
The latest questions for the topic "calculations"Decrease character controller velocity by percent each frame
http://answers.unity.com/questions/1787854/decrease-character-controller-velocity-by-percent.html
I've been trying to wrap my head around how you would go about reducing the player's speed by a certain percentage each frame. The motive for this is to achieve framerate independent ground friction for a character controller. The issue is that using multiplication on a frame by frame basis seems impossibly difficult to account for to reach framerate independent friction.
private void applyFriction()
{
Vector3 tempVelocity = playerVelocity;
tempVelocity.y = 0;
tempVelocity = tempVelocity - (Time.fixedDeltatime * tempVelocity);
//assuming a timestep of 0.02 seconds, then roughly tempVelocity should decrease by 1/50th of itself every 0.02 seconds at 50 physics calculations per second.
//since velocity changes on a frame by frame basis, and since fixedDeltaTime could fluctuate, then how do we account for this change?
velocity.x = tempVelocity.x; velocity.z = tempVelocity.z;
}
In practice, given a Vector3 (representing velocity), how can you reduce the Vector3's magnitude by a certain percentage each second?
*Or as a more general question, what is the best way to handle friction for a character controller?* What formula would I apply to tempVelocity in order to slow the character down by a certain percentage every second?physicscharactercontrollercharacter movementfrictioncalculationsThu, 12 Nov 2020 04:28:58 GMTxthunderduckxURGENT HELP How to add "+,-,x, / and =" to my 3D Calculator
http://answers.unity.com/questions/1783394/urgent-help-with-a-3d-calculator-that-you-can-jump.html
Hi I'm making a 3d calculator that you can jump on each individual number for it to show up on the screen. but it only shows one number at a time and doesn't do the calculators basic functions such as addition, subtraction and also working out the total could someone help me on what i need to add to get this to work.
Script i have so far:
public float firstNumber = 0f, secondNumber = 0f;
float product = 0f;
public TextMeshProUGUI text;
string op;
public void Value(float value)
{
if (op == null)//** Let's us continue
{
firstNumber = value;
text.text = firstNumber.ToString() + " ";
}
else
{
secondNumber = value;
text.text += secondNumber.ToString() + " ";
}
}
//this means the script needs to be on the player
void OnTriggerEnter(Collider other)
{
if ( other.gameObject.CompareTag("button"))
{
Debug.Log(firstNumber.ToString());
Value(float.Parse(other.gameObject.name));
}
}
public void Operation(string operation)
{
if (operation == "+")
{
op = "+ ";
}
else if (operation == "-")
{
op = "- ";
}
else if (operation == "=")
{
Calculate();
}
text.text += op;
}
void Calculate()
{
if (op == "+ ")
{
product = firstNumber + secondNumber;
}
else if (op == "- ")
{
product = firstNumber - secondNumber;
}
text.text += "= " + product.ToString();
//Resets
op = null;
firstNumber = product;
secondNumber = 0;
}
}beginnercalculationcalculationsbeginnersMon, 26 Oct 2020 11:22:30 GMTunity_10783358Finding the intersection of vertical plane and scene mesh geometry
http://answers.unity.com/questions/1731511/finding-the-intersection-of-vertical-plane-and-sce.html
I need to find all the intersections of an upright plane with the main character's position and rotation. I currently have some code that works but is spewing out some strange values. In my code, I convert the 3-dimensional edges of all the meshes into two-dimensional equations in the form of Ax + By = C with bounds. I make an equation for the plane with the same form and calculate their intersection. If the intersection is within the edge's bounds, it calculates the percentage along the line from point 1 to point 2 and uses that the calculate a 3d position where the intersection takes place.
Here is my code:
public class Edge
{
public Vector3 p1;
public Vector3 p2;
public LineEquation Xequation;
public LineEquation Yequation;
public LineEquation Zequation;
public BoxRange Range;
public float Length;
public Edge(Vector3 p, Vector3 pp)
{
p1 = p;
p2 = pp;
float x = Mathf.Abs(p.x - pp.x);
float y = Mathf.Abs(p.y - pp.y);
float z = Mathf.Abs(p.z - pp.z);
Xequation = new LineEquation(new Vector2(p.y, p.z), new Vector2(pp.y, pp.z));
Yequation = new LineEquation(new Vector2(p.x, p.z), new Vector2(pp.x, pp.z));
Zequation = new LineEquation(new Vector2(p.x, p.y), new Vector2(pp.x, pp.y));
Range = new BoxRange(p, pp);
Length = (p - pp).sqrMagnitude;
}
}
public class LineEquation
{
public float A, B, C;
public LineEquation(float a, float b, float c)
{
A = a;
B = b;
C = c;
}
public LineEquation(Vector2 p1, Vector2 p2)
{
A = p2.y - p1.y;
B = p1.x - p2.x;
C = A * p1.x + B * p1.y;
}
public LineEquation(Vector2 p, float angle)
{
angle *= Mathf.Deg2Rad;
Vector2 p2 = new Vector2(p.x + Mathf.Sin(angle), p.y + Mathf.Cos(angle));
A = p2.y - p.y;
B = p.x - p2.x;
C = A * p.x + B * p.y;
}
}
public class BoxRange
{
public Vector3 lowerBound;
public Vector3 higherBound;
public BoxRange(Vector3 p1, Vector3 p2)
{
lowerBound = new Vector3(
Mathf.Min(p1.x, p2.x),
Mathf.Min(p1.y, p2.y),
Mathf.Min(p1.z, p2.z)
);
higherBound = new Vector3(
Mathf.Max(p1.x, p2.x),
Mathf.Max(p1.y, p2.y),
Mathf.Max(p1.z, p2.z)
);
}
}
public class PlaneCaster
{
public Edge[] edges;
public string layer { get; private set; }
public PlaneCaster(string tagLayer)
{
layer = tagLayer;
GameObject[] list = GameObject.FindGameObjectsWithTag(tagLayer);
List<Edge> buffer = new List<Edge>();
for (int i = 0; i < list.Length; i++)
{
Vector3 scale = list[i].transform.localScale;
Vector3 pos = list[i].transform.position;
Mesh mesh = list[i].GetComponent<MeshFilter>().sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
for (int j = 0; j < triangles.Length / 3; j++)
{
Edge edge1 = new Edge(Vector3.Scale(vertices[triangles[j * 3]], scale) + pos, Vector3.Scale(vertices[triangles[j * 3 + 1]], scale) + pos);
Edge edge2 = new Edge(Vector3.Scale(vertices[triangles[j * 3 + 1]], scale) + pos, Vector3.Scale(vertices[triangles[j * 3 + 2]], scale) + pos);
Edge edge3 = new Edge(Vector3.Scale(vertices[triangles[j * 3 + 2]], scale) + pos, Vector3.Scale(vertices[triangles[j * 3]], scale) + pos);
if (!CheckMatch(buffer, edge1)) buffer.Add(edge1);
if (!CheckMatch(buffer, edge2)) buffer.Add(edge2);
if (!CheckMatch(buffer, edge3)) buffer.Add(edge3);
}
}
edges = buffer.ToArray();
}
public void DrawPlaneRay(Vector3 pos, float rot)
{
rot *= Mathf.Deg2Rad;
LineEquation plane = new LineEquation(new Vector2(pos.x, pos.z), rot);
Debug.DrawRay(pos, new Vector3(Mathf.Sin(rot), 0f, Mathf.Cos(rot)), Color.green, 0.1f, false);
}
public void DrawDebug()
{
for (int i = 0; i < edges.Length; i++)
{
Debug.DrawLine(edges[i].p1, edges[i].p2, Color.red, 2f, false);
}
}
private bool CheckMatch(List<Edge> buff, Edge check)
{
for (int i = 0; i < buff.Count; i++)
{
if (
(buff[i].p1 == check.p1 && buff[i].p2 == check.p2) ||
(buff[i].p1 == check.p2 && buff[i].p2 == check.p1)
)
{
return true;
}
}
return false;
}
public List<Vector3> Cast(Vector3 pos, string axis, float rot)
{
List<Vector3> result = new List<Vector3>();
LineEquation plane;
if (axis == "x") plane = new LineEquation(new Vector2(pos.y, pos.z), rot);
else if (axis == "y") plane = new LineEquation(new Vector2(pos.x, pos.z), rot);
else if (axis == "z") plane = new LineEquation(new Vector2(pos.x, pos.y), rot);
else throw new Exception("Undefined Axis");
for (int i = 0; i < edges.Length; i++)
{
try
{
Vector2 reference;
if (axis == "x") reference = new Vector2(edges[i].p1.y, edges[i].p1.z);
else if (axis == "y") reference = new Vector2(edges[i].p1.x, edges[i].p1.z);
else if (axis == "z") reference = new Vector2(edges[i].p1.x, edges[i].p1.y);
else throw new Exception("Undefined Axis");
Vector2 intercept = GetIntercept(i, axis, plane);
if (
(axis == "x" && intercept.x > edges[i].Range.lowerBound.z && intercept.x < edges[i].Range.higherBound.z && intercept.y > edges[i].Range.lowerBound.y && intercept.y < edges[i].Range.higherBound.y) ||
(axis == "y" && intercept.x > edges[i].Range.lowerBound.x && intercept.x < edges[i].Range.higherBound.x && intercept.y > edges[i].Range.lowerBound.z && intercept.y < edges[i].Range.higherBound.z) ||
(axis == "z" && intercept.x > edges[i].Range.lowerBound.x && intercept.x < edges[i].Range.higherBound.x && intercept.y > edges[i].Range.lowerBound.y && intercept.y < edges[i].Range.higherBound.y)
)
{
float dist = (reference - intercept).sqrMagnitude;
float perc = dist / edges[i].Length;
result.Add((edges[i].p1 * (1f - perc)) + (edges[i].p2 * perc));
}
}
catch(Exception e)
{
}
}
return result;
}
public Vector2 GetIntercept(int index, string axis, LineEquation eq)
{
LineEquation line;
if (axis == "x") line = edges[index].Xequation;
else if (axis == "y") line = edges[index].Yequation;
else if (axis == "z") line = edges[index].Zequation;
else
{
throw new Exception("Axis is Incorrect");
}
float delta = line.A * eq.B - eq.A * line.B;
if (delta == 0)
throw new Exception("Lines are Paralell");
float x = (eq.B * line.C - line.B * eq.C) / delta;
float y = (line.A * eq.C - eq.A * line.C) / delta;
return new Vector2(x, y);
}
}
![alt text][1]
![alt text][2]
In the images above, the green line represents the plane's rotation, the red lines are all the calculated edges in the scene and the blue lines are lines going from the main player to the points of intersection. In theory, all of the blue lines should be parallel with the green line.
Any help in finding the problem with my code is appreciated.
[1]: /storage/temp/159675-capture.png
[2]: /storage/temp/159676-capture1.pngplanegeometrylinesintersectioncalculationsMon, 18 May 2020 06:06:08 GMTargentummanusbetaThe number of ammos are working correctly on unity, but its showing false(default values) when i play on phone, HELP PLEASE ?
http://answers.unity.com/questions/1729905/the-number-of-ammos-are-working-correctly-on-unity.html
![alt text][1]
I am using **Start()** method to add ammo as *Float* **according to points**.
Its showing as - 88 on unity this is correct,
**But when on phone its showing as - default value(0..)**.
*help?*
[1]: /storage/temp/159343-saddddd.pngnot workingmobile devicesfloatingwrongcalculationsWed, 13 May 2020 03:45:48 GMTEnesT72Vector3.distance wrong distance calculating?
http://answers.unity.com/questions/1684795/vector3distance-wrong-distance-calculating.html
I have `Player` object and `Enemy` object. `Enemy` is always stalking `Player` and trying to kill him. In function that sends damage to `Player` i use `Vector3.distance` to calculate disance between two objects and here strange things begin to appear: **If i move `Enemy` prefab from editor to scene *manually* everything works fine**, distance calculates correctly and `Enemy` sends damage to `Player` as it comes close enough. **But if I *`Instatiate` the same `Enemy` prefab via script* `Vector3.Distance` begins to calculate the distance from the `Enemy` to some point located at the other end of the map, where there is literally nothing.** There are no objects with the same tag (Im referencing Player GameObject to Enemy using `FindGameObjectWithTag`). Because of that Enemy can't hit Player.
Interestingly, to calculate the movement of the enemy to the player, I use the function `Vector3.MoveTowards`with the same referencing to Player GameObject and it works fine in both cases.
i.e. if Enemy was Instatiated via script, it can move to Player but cannot hit him because the distance is calculated incorrectly
I ask you not to say that the `FindGameObjectWithTag` operation is heavy and "costs" some computing power, I know it
Reference for `Vector3.Distance()`:
void Start()
{
Target = GameObject.FindGameObjectWithTag("Player");
}
Vector3.Distance(Target.transform.position, transform.position)
Reference for `Vector3.MoveTowards()`:
void Start()
{
Target = GameObject.FindGameObjectWithTag("Player");
}
Vector3.MoveTowards(transform.position, new Vector3(Target.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
Game is in 2D spacedistancecalculatecalculationsSun, 15 Dec 2019 16:54:06 GMTbyalexeykhCalculate 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 GMTdeveloperation1Calculate launch angle based on launch direction
http://answers.unity.com/questions/1633663/calculation-launch-angle-based-on-launch-direction.html
I'm working with a setup like this:
![alt text][1]
[1]: /storage/temp/138588-vectors.jpg
Where the vectors all start at transform.position and end as follows:
- Black: transform.position + HandlePosition
- Blue: transform.position + Vector2.right
- White: transform.position - HandlePosition.normalized
The idea is that i can move the red handle around to change the White vector (the launch direction of the object).
Now what I would like to get is the angle between the White and Blue vectors.
I want to get this angle so that I can calculate the trajectory of the object and display a trajectory line.
**Edit:**
Given the example shown on the picture, I would expect an angle of about 45 degrees.mathanglevectoranglescalculationsTue, 21 May 2019 16:46:58 GMTMalyglutRaycast Down with Approximation Search
http://answers.unity.com/questions/1606745/raycast-down-with-approximation-search.html
I've got an approximation search and would like to ad from the BezierCurve Point the Point on the Ground. => but for correct Result the Point on the Ground must be calculated every Time on the approximation search (*due to correct distances*)
<br>
***Approximation Search Code***:
<br>
float step = 0.1f;
float t = step;
float lastT = new float();
float distance = 5;
/* Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t) is a Vector3 Equation for a Point on the Bezier Curve */
while (t >= 0 && t <= 1f)
{
while (t < 1f && Vector3.Distance(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t), last_spawn) < distance){
t += step;}
step /= 100;
while (t > lastT && Vector3.Distance(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t), last_spawn) > distance){
t -= step;}
step /= 100;
if (t > 1f || t < lastT){
break;}
if(step < 0.000001f){
myList.Add(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t));
lastT = t;
step = 0.1f;
}
}
(*Pseudo Code*)
<br>
Now because the BezierLine is never really aligned with the Surface (*Terrain*) I need to get the Point on the Ground. If I now Add following `Vector3.RaycastDown_Position();` to the `Bezier.GetPoint(a,b,c,d,t);` Method => `Bezier.GetPoint(a,b,c,d,t).RaycastDown_Position();`
the Editor will freeze and get's Laggy!
<br>
***Raycast Down Code***
<br>
public static Vector3 RaycastDown_Position(this Vector3 t){
RaycastHit hit;
if(Physics.Raycast(t + (Vector3.up * 20),Vector3.down,out hit,Mathf.Infinity)){
t.y = hit.point.y;
}
return t;
}
<br>
**Question:**
What would be a better Approach to avoid Laggy Editor, or even Freezes?
<br>
if I add the RaycastDown Method after the approximation search, it'l cause inaccurate Result at the distance between the Calculated Points!
thanks @Bunny83 for any suggestion =)c#raycastvector3beziercalculationsTue, 26 Feb 2019 18:57:49 GMTdan_wipfHow to calculate distance traveled given time and speed
http://answers.unity.com/questions/1557048/how-to-calculate-distance-traveled-given-time-and.html
Hey guys, I'm trying to figure this out but so far not as good as it should be, so of course I'm doing something wrong. So in my game I'm throwing a ball based on a power bar, this power bar only affects speed but the ball always travels the same amount of time which is 2 seconds. What I'm trying to do is add a crosshair to predict how far the ball will travel according to the current power.
The balls Update method runs this code:
protected virtual void Update () {
transform.Translate(transform.up * speed * Time.smoothDeltaTime * power);
}
Power is a float that goes from 0 up to 1, max. The thing is I can't get the crosshair to actually mark the correct spot, here's my update method for the crosshair:
void Update () {
Vector3 newPosition = transform.position;
newPosition.y = (totalRange * power) + minY ;
transform.position = newPosition;
}
That class has a minY and a maxY which are calculated given the camera size, and the totalrange is the sum of minY's absolute value and maxY. The thing is, for the maximum or minimum value of power the results are correct given the size of the camera but its not accurate for the travel distance of the ball since it moves exponentially, for example, the ball barely moves with a power less than 0.15. I know that Distance = Speed * Time, Time I know, but a speed when the ball moves with translate?
Anyway, I guess is something stupid that I can't get my head around of due to the lack of sleep xD
Thank you all for reading me!
**Edit**: So I finally got it working, in the end I was forgetting about those 2 seconds in my formula, so I ended up doing (totalRange * power * smoothDeltaTime * TravelTime * framerate) + minY
All I needed was a good night sleep. Of course, since movement and calculation is based on framerate, I'll provide an area estimation which is pretty close, in all my tests the ball falls practically on the spot, sometimes with a 0.05 - 0.10 offset, therefor I'll provide some area icon so the player knows it's going to fall pretty close to the target area.movementtransform.positiondistance checkcalculationsWed, 26 Sep 2018 19:19:07 GMTEyeOfDBeholderMultiple projectiles hitting the same target at once for shotguns
http://answers.unity.com/questions/1551307/multiple-projectiles-hitting-the-same-target-at-on.html
Basically, I am working on a FPS game with sort of physical projectiles. The projectiles have a component attached containing the values for damage, velocity etc. and the "Player" component of the player who fired the projectile (I call that the "owner" of the projectile). The amount of damage the projectile has done is sent back to the owner and is then displayed in their UI (similar to Battlefield) to keep track of the players score. Let's say I have a gun which deals 30 damage, the number in the UI will go from 30 to 60 to 90 to 100. I achieve that the number doesn't exceed 100 using the code below.
This works perfectly fine for normal weapons which fire one projectile at a time, however, with a shotgun which fires multiple projectiles at once (I use a for-loop spawning one projectile each time for that) I run into the problem that the projectiles hit almost simultaneously and the math doesn't seem to be able to keep up. Essentially, every projectile "thinks" the target is still at full health and therefore sends back it's full potential damage to the owner, leading to the owner of the projectiles earning considerably more than 100 score with a single shot.
I have some possible solutions in mind, one which I have tried so far is giving each projectile a random delay by calling CmdPlayerHit with a coroutine with a random yield time between 0 and 0.2s, which obviously also means that the damage is delayed which isn't really great for a FPS. An alternative I coul think of would be to store the amount of damage a projectile has done in a variable on the owner, add them all together and clamp the combined damage so it doesn't exceed the damage when the player was hit by the first projectile, however, I have no idea when I would then "apply" this score as some projectiles might hit a different target at a different time.
If someone has an idea, a comment or a similar problem feel free to answer. Any help appreciated.
The function below is called when the projectile has hit a player.
[Command]
void CmdPlayerHit (string _playerID, float _damage)
{
Debug.Log(_playerID + " has been hit by " + ownerID);
Player _player = GameManager.GetPlayer(_playerID); //gets the "Player" component of the target
float previousHealth = _player.GetCurrentHealth(); //returns the current health of the shot player
_player.RpcTakeDamage(_damage); //makes the shot player take damage
float score = Mathf.Max(Mathf.Min(_damage, previousHealth), 0f); //change the damage to a appropriate number
owner.RpcAddRecentDamagePoints(score); //give the owner the score
}c#projectileclampcalculationsshotgunSun, 09 Sep 2018 16:01:57 GMTGlitshyTrajectory line throwing downward
http://answers.unity.com/questions/1537607/trajectory-line-throwing-downward.html
Hello,
i've got a ball which i adjust force to. It's very angry birds like. The ball goes in the opposite direction you drag the mouse. (screenshots attached)
For this i want to draw a trajectory line and everything works fine. But when I want to shoot the ball downwards the wrong coordinates for the points of the LineRenderer are calculated.
Maybe you can help me and tell me what I'm doing wrong!
----------
private LineRenderer lr;
public float velocity, angle;
public int resolution = 10;
private float g;
private float radianAngle;
public void RenderArc(float v, float a)
{
velocity = v;
angle = a;
lr.positionCount = resolution + 1;
lr.SetPositions(CalculateArcArray());
}
Vector3[] CalculateArcArray()
{
Vector3[] arcArray = new Vector3[resolution + 1];
radianAngle = Mathf.Deg2Rad * angle;
float maxDistance = (velocity * velocity * Mathf.Sin(2 * radianAngle)) / g;
for (int i = 0; i <= resolution; i++)
{
float t = (float) i / (float) resolution;
arcArray[i] = CalculateArcPoint(t, maxDistance);
}
return arcArray;
}
Vector3 CalculateArcPoint(float t, float maxDistance)
{
float x = t * maxDistance;
float y = transform.position.y + x * Mathf.Tan(radianAngle) -
(g * x * x) / (2 * velocity * velocity * Mathf.Cos(radianAngle) * Mathf.Cos(radianAngle));
x += transform.position.x;
return new Vector3(x, y, 0.0f);
}linerenderertrajectorylaunchcalculatecalculationsThu, 02 Aug 2018 21:13:22 GMTCreativeBrainstormPositioning a point on a bended Mercator world map
http://answers.unity.com/questions/1501010/positioning-a-point-on-a-bended-mercator-world-map.html
I have created a bended 3d view holding a world map based on Mercator projection, as follows:
![alt text][1]
I want to a script to place the blue marble in the right place, using lat & long coordinates. I have used the following function to try to convert to Mercator, but my map is on a bended mesh (50 degrees) and I don't really know how to transform the x,y coordinates and how to computer the z coordinate.
// Project a geographic coordinate on the (spherical) Mercator map.
// Using the mean between major an minor axis here ("PTV standard").
// You could also use the major axis 6378137 ("Google standard").
public Vector3 LatLonToSphereMercator(float xradius, float yradius, float latitude, float longitude)
{
float x = xradius * longitude * Mathf.PI / 180;
float y = yradius * Mathf.Log(Mathf.Tan(Mathf.PI / 4 + latitude * Mathf.PI / 360));
return new Vector3 (x, y, 0);
}
What would be the best way to achieve this? Thanks in advance!
[1]: /storage/temp/116075-map.gifpositioningmapscalculationsbendingWed, 02 May 2018 06:36:22 GMTdtylmanCalculating mesh area
http://answers.unity.com/questions/1474675/calculating-mesh-area.html
I have a game with the shape slicing mechanics.
I need to get the area (it's in 2D) of the each slice. Each slice has Mesh, PolygonCollider2D and RigidBody2D.
How can I get a slice area using existing components?
The area must represent actual object size on screen and should know about object scale.
Rect and bound solutions don't have a good accuracy with complex shapes like stars. So I'd already tried them.meshgeometrycalculationsWed, 28 Feb 2018 15:45:10 GMTinterpol_kunAdjust Ortographic Camera Size so it fits objects of my scene automatically
http://answers.unity.com/questions/1456674/adjust-ortographic-camera-size-so-it-fits-an-objec.html
I want to make a script that ajusts my Ortographic Camera Size so it fits the objects in my scene, but I have no idea how.
![alt text][1]
For the position of the camera, I guess I can use Bounds to find the center and position my camera according to it.
For the Size I have no idea.
[1]: /storage/temp/109553-camera-problem.pngcamerasceneobjectsboundscalculationsThu, 18 Jan 2018 19:45:41 GMTdavidrochinDoes GUIStyle.CalcSize harm the performance?
http://answers.unity.com/questions/1426764/does-guistylecalcsize-harm-the-performance.html
I have been doing an inventory system lately I have been using the `GUILayout` functions for soo long time but after knowing that it does harm the performance if it is used extensively so, I switch to the good old normal `GUI` functions.
Now I have come across a function known as `GUIStyle.CalcSize();` so, I began using it and was wondering does it harm the performance if used let's say 25 times per frame?
Thanks in advance!guiuiguilayoutcalculationsFri, 27 Oct 2017 20:06:33 GMTWinterboltGamesProblem operating with doubles
http://answers.unity.com/questions/1426346/problem-operating-with-doubles.html
Probably will sound a stupid question but I have:
double value = 0;
value = 2 - (10 / 20);
return value ; // return 2
and testign with d
double value = 0;
value = 2 - (10 / 20d);
return value ; // return 1.5
How should I work with doubles? have to add "d" next to a value with a possible decimal result??? How this exactly works? I dont want to check AAAAALLLL my code and testing each operation!
Thank you.operatordoublecalculationsThu, 26 Oct 2017 20:34:04 GMTArkshijaHow to optimize big numbers calculatation. Not exact transform position when I'm moving on a far distance from a zero point
http://answers.unity.com/questions/1424484/how-to-optimize-big-numbers-calculatation-not-exac.html
I have a camera with one game object in child of it. When I'm moving near the start point (0,0,0) everything does right, but when I'm on thousand units from start point the child of the camera is wobbling, the furter from the start point the stronger is wobbling. I understand why it is, but i want to know how I can optimize it. Sorry for my english if something is not correct.transformoptimizationdistancecalculationsMon, 23 Oct 2017 11:05:09 GMTPandrPiRound the cube consists of planes (Planetary terrain's chunks proplem).A problem with inverseTransformPoint and TransformPoint functions
http://answers.unity.com/questions/1421022/sphere-from-chunks-planes-problem.html
Hi,
I have a problem with inverseTransformPoint and TransformPoint functions.
Below is partial answer on my question
http://answers.unity3d.com/questions/1101723/plane-to-sphere-issue.html
and its works fine when the planes (chunks) are around verctor3.zero such as on the screenshots in the link above. My problem is that i don't understand how this method can work if i move planes to another position( to 10,10,10 for example, or to any else).
Thanks for attention.transformmeshverticescalculationsinversetransformpointSun, 15 Oct 2017 15:43:03 GMTPandrPiStackoverflow by too many calculations?
http://answers.unity.com/questions/1299258/stackoverflow-by-too-many-calculations.html
Is it possible by to get the stack overflow exception dued to too many calculations in a single frame?
I have a function that calculates and compares the difference between 20 vector3 in a single frame.
It submits the vector with the smallest distance,t to a coroutine and than restarts it.
the coroutine moves an object to a vector3 wich can be exchanged by the aforementioned function.
note that the coroutine runs fine before the function is triggered!
when the function starts it's calculation I get a fps drop to "0" before getting the stackoverflow exception notice and the game runs on but doesn't execute the coroutine anymore.
however the calculations are finished and the nearest vector3 is passed to the coroutine.
in a nutshell (coroutine=fine -> huge calculation -> change coroutine value -> restart coroutine -> stackoverflow)
I won't post any code right now, since it's rather just a question about the stackoverflow in general, since I couldn't find it's correct meaning.
However if you really wanna help me debugging it, I will post the code.
Thanks a lot!
kayb14c#coroutinescoroutine errorscalculationsstackoverflowSun, 15 Jan 2017 05:41:48 GMTkayb14Adjust scale of object based on distance to maintain same perceived size
http://answers.unity.com/questions/1292437/adjust-scale-of-object-based-on-distance-to-mainta.html
Hi all,
Having a little trouble explaining what I am trying to do so please bear with me.
I am working on a demo that involves massive scales in the space. To make things more manageable I want to do is keep the planets closer together in game units, but scale them so that they appear to be the real world size as seen from that location.
For example let's say the camera is at the Earth. Instead of putting the sun 150 million kilometers away and making it have a radius of 695,700km, I want to put it say just 10,000 meters away from the Earth but scale it down (some unknown amount) so that the PERCEIVED size would be the same.
However despite an hour or so of Googling I can't seem to figure out how to calculate the scale factor based on distance. I ran into some topics about perceived angle, but I don't understand what that means, nor how I could even translate an "angle" into a size in game.
I feel like I am close to the answer, spiraling in on it but not quite hitting it. Here is the code I am currently using. This is in C#
Vector3d activeRealPosition = activeBody.GetOrbitPosition("real");
Vector3d activeGamePosition = activeBody.GetOrbitPosition("play");
Vector3 realOrbitPosition = Vector3.zero;
Vector3 actualOrbitPosition = Vector3.zero;
if (TypeOfBody != BodyType.Star)
{
realOrbitPosition = transform.TransformPoint(_orbits["real"].position); // CelestialOrbit stores position in local space
actualOrbitPosition = transform.TransformPoint(_orbits["play"].position);
}
double realDistance = Vector3d.Distance(activeRealPosition, realOrbitPosition);
double actualDistance = Vector3d.Distance(activeGamePosition, actualOrbitPosition);
Debug.Log("Real Distance: " + realDistance + ", Actual Distance: " + actualDistance);
// actual distance should always be much smaller than real distance
if (actualDistance > realDistance)
Debug.LogWarning("[UpdateScale] Actual distance is larger than real distance");
double difference = (realDistance - (realDistance-actualDistance)) / (realDistance);
Debug.Log("Difference: " + difference);
double newScale = RealRadius * difference;
transform.localScale = Vector3.one * (float)newScale;
I am basing it on some manual tests I did just positioning two objects at different distances and looking if they appear the same size, and in those manual setups they did. So I then tried to apply that math to the real deal, but it doesn't work. The math is based on: http://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.phpscalemathcalculationsSat, 31 Dec 2016 05:42:08 GMTjwvanderbeckHow do you create a continuous physics simulation in Unity?
http://answers.unity.com/questions/1262902/how-do-you-create-a-continuous-physics-simulation.html
So I want to make a game with planets (and other celestial objects) orbiting stars (and other stuff).
I want to be able to predict the path of an object in the future and display where it is going to move.
I know that the 'n-body problem' is unsolved, so only small objects that won't exert any force of gravity will be actually move - all other objects will have fixed positions.
So basically the force (and therefore the acceleration) of any of my moving objects will be a function of position.
But now I want to predict their paths. I want to do this with calculus, so that I can get an exact value for an object's position at any given time, without making lots of expensive calculations.
However, since Unity does not have built in functionality for this kind of simulation, I am going to have to set the force on the moving objects each frame in FixedUpdate() based on their masses and positions relative to the gravity-exerting stars. This means there will always be a constant force on an object throughout a single Physics Time-step. Therefore, my calculation that predicts the position of the object at any given time using calculus will not be accurate because it assumes a continuous change of force based on continuous movement.
Is the only solution to essentially create my own physics system that uses calculus to work with continuous gravitational forces from the stars and use this to set the position of each moving object directly each frame?
/*Side Note: I was also thinking about other possible scenarios in the physics engine and I was wondering how this issue is solved in other cases.
Presumably Unity's physics engine sometimes has to work with forces (and torques etc.) that should change throughout a Physics Time-step. (Eg. Collisions?)
How does Unity handle this? Does it just approximate that the force would stay constant through out the Time-step and calculate what would happen with constant values of all the variables.*/physicsgravityspacesimulationcalculationsWed, 26 Oct 2016 22:29:44 GMTJosp101Timer issues when converting to minutes,hrs,days,months,years
http://answers.unity.com/questions/1246051/timer-issues-when-converting-to-minuteshrsdaysmont.html
got an issue with my timer, i am trying to store a single sequence of seconds and convert that to minutes, hours, days, months, years
if (Time.time > nextTime)
time += 1.4f;
nextTime = Time.time + 1.4f;
print("minutes " + Mathf.RoundToInt(time / 60f) + " Hours " + string.Format("{0}", hours));
}
the issue is i am unable to reset the minutes, hours etc back to 0 once they reach the maximum
minutes = 60, hours 24, days 7, weeks 4, months 12
is their a maths formula i could use to convert this.timercalculationmathscalculationsformulaTue, 20 Sep 2016 11:11:13 GMTRealSoftGamesHow to get the distance between two objects in feet/meter?
http://answers.unity.com/questions/1218591/how-to-get-the-distance-between-two-objects-in-fee.html
Hi,
I am working on a project where i should measure the distance between two object in meter or feet.
I can calculate the vector3 distance between two objects, but i dont know how to convert it to the meter or feet.
can anyone please help to how to do this ?
Thanks.c#raycastdistancemathcalculationsWed, 20 Jul 2016 09:11:19 GMTschettyWrong result although code should be correct.
http://answers.unity.com/questions/1217565/wrong-result-although-code-should-be-correct.html
Hello, I have this little project here which actually seems quite simple. I have to calculate the destination, given start point, distance and bearing. I have done some research and found this:
![alt text][1]
With the same values my programm spits this out:
![alt text][2]
My programm-code:
import UnityEngine.UI;
//INPUT STRINGS
var input1 : String;
var input2 : String;
var input3 : String;
var input4 : String;
//INPUT FIELDS
var inputF1 : InputField; //input Field 1
var inputF2 : InputField; //__""__ 2
var inputF3 : InputField; //...
var inputF4 : InputField; //...
var result : Text;
private final var R : float = 6371000; //Earth's radius in metre
//INPUT VARIABLES
var d : float; //distance to travel
var a1 : float; //latitude in dezimals
var b1 : float; //longitude in dezimals
var brng : float; //Angle you are going to
function Start () {
}
function Update () {
}
//
//BUTTON FUNCTIONS
//
function ExitButton(){
Application.Quit();
}
function InputF1(){
input1 = inputF1.text;
}
function InputF2(){
input2 = inputF2.text;
}
function InputF3(){
input3 = inputF3.text;
}
function InputF4(){
input4 = inputF4.text;
}
function Calc(){
d = float.Parse(input3);
a1 = float.Parse(input1);
b1 = float.Parse(input2);
brng = float.Parse(input4);
brng = brng * Mathf.Deg2Rad;
a1 = a1 * Mathf.Deg2Rad;
b1 = b1 * Mathf.Deg2Rad;
var a2 : float = Mathf.Asin( Mathf.Sin(a1)*Mathf.Cos(d/R) +
Mathf.Cos(a1)*Mathf.Sin(d/R)*Mathf.Cos(brng) );
var b2 : float = b1 + Mathf.Atan2(Mathf.Sin(brng)*Mathf.Sin(d/R)*Mathf.Cos(a1),
Mathf.Cos(d/R)-Mathf.Sin(a1)*Mathf.Sin(a2));
result.text = a2 * Mathf.Rad2Deg+"°N "+b2 * Mathf.Rad2Deg+"°W ";
}
//
//BUTTON FUNCTIONS END
//
My input is the same and strangely the first value (a2 in my script), latitude is always exactly right. The longitude however is always off by quite a bit. I have compared the two scripts over and over again. I just can´t figure out what the problem is.
[1]: /storage/temp/74303-pic1.png
[2]: /storage/temp/74305-pic2.png
I am not asking for any scripts, but some help would be awesome!
Anything that I could have missed?
Anyways, thanks for the help in advance!calculationcalculationsMon, 18 Jul 2016 06:12:10 GMTDonkeyMalonkeyCan't seem to round to 2 DP
http://answers.unity.com/questions/1205727/cant-seem-to-round-to-2-dp.html
I am making a slot machine game and the winning point should be in 2 decimal places to symbolize money, i tried both System.Math and Mathf.Round but none of them seems to work. Are there any other ways that will work? Here's my code:
linesInfo.lineInfo[a].winningValue = System.Math.Round((iconInfo[payoutIcon.ID].xTwo * betAmounts[currentBet] / lineCount) * 100) / 100;mathvaluecalculationsroundTue, 21 Jun 2016 02:50:02 GMTn931009How to calculate vector perpendicular to a direction vector?
http://answers.unity.com/questions/1203255/how-to-calculate-vector-perpendicular-to-a-point-o.html
Hello,
I am trying to get the direction of the vector perpendicular to the direction vector of 2 points(A,B) illustrated below. I understand a cross product requires a reference vector like transform.right to work, but I get weird behavior when the direction(dir) vector is equal to the reference vector transform.right: the rigidbody2d I am moving with it just wobbles back and forth.
P.S. using the rigidbodies transform.right would be good, but it's always rotating, so that can't work.
Any physics-related suggestions are appreciated!
void Rotate(Rigidbody2D rb)
{
Vector3 dir = rb.transform.position - transform.position;
dir.Normalize();
Vector3 side = Vector3.Cross(dir, -transform.right);
Vector3 cross = Vector3.Cross(dir, side);
rb.AddForce(cross.normalized * speed);
}
![alt text][1]
[1]: /storage/temp/72219-untitled-1.png2dmathcirclevectorscalculationsWed, 15 Jun 2016 19:15:47 GMTAndrewRyanHow to calculate angular velocity of target relative to player object
http://answers.unity.com/questions/1193788/how-to-calculate-angular-velocity-of-target-relati.html
I am working on a game that has some vehicle weapons that will track locked on targets. To add some realism, I am making it so that the angular velocity of the target (relative to the player/attacker) affects the success rate of the automated weapon.
Let us assume for right now that the speed of the projectiles the attacker is shooting at the target is not important for our calculations (consider instant for now)... only the ability of the gun to swivel fast and accurately enough to keep up with the target is important for now. Also, let us ignore how fast the target is moving towards or away from the attacker.
Additionally, this need to take into effect the rotation of the player as well. If the player turns away from the target as the weapon is trying to home in, this should add to the relative angular velocity of the target. Also, just to be clear, we are looking for how fast a target APPEARS to be going relative to the attacker, not actual velocity (far away would appear slower, point blank would appear much faster).
I am new to 3d game design and this is a little outside of my skill level. Thank you for any assistance you can give.
TL;DR - Need to calculate perceived angular velocity of target relative to player angular velocity.c#calculationsSat, 28 May 2016 05:19:42 GMTProtoNoobcalculate velocity vector based on direction
http://answers.unity.com/questions/1177136/calculate-velocity-vector-based-on-direction.html
Hi folks,
I'm new to unity and currently I'm running some tests. One test is a power up a player can obtain. I want the player accelerated into the direction the powerup is faceing. Since it is a 2D game the direction is tied to the z-rotation. 0=up, 90=left, 180=down, 270=right. So if the power up is rotated at 90° i want a force applied to the player. This is easy for the base direction, 0,90,180 and 270.
But how do i calculate the vector for e.g. 22° oder 98°?
I must admit my math knowledge is long gone and I'm currently working my way back to what i used to know. But until then i would appreciate a little hint :)
Thanks in advance,
Marcvelocityforcevector2calculationsTue, 26 Apr 2016 16:27:22 GMTmercsenUnity3D - Get smooth speed and acceleration with GPS data
http://answers.unity.com/questions/1176439/unity3d-get-smooth-speed-and-acceleration-with-gps.html
Hi, I created simple distance, speed and acceleration calculator using latitude and longitude of last position. I'm calculating last distance, speed and acceleration in each GPS update (approximately once per second). But sometimes (2-3 second interval) latitude and longitude values changes rapidly (in clear weather and no obstacles). That's why speed and acceleration values gets unreal results. For example, at stable 40 km/h speed, speed value becomes 60 km/h and returns to 40 km/h within 2-3 second. I'm here to ask how can I avoid this inaccurate and rapid GPS data changes?
I'm using Nexus 5 device
There is my code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Manager : MonoBehaviour
{
public Text longitude, latitude, lonAText, latAText, lonBText, latBText;
public Text result, overallResult, speedText, lastTimeText, timerText, accelerationText, speed0Text;
float lonA, lonB, latA, latB, overallDistance, lastDistance, timer, lastTime, speed, speed0, acceleration;
bool firstTime, allowTimer;
public AudioSource audio;
void Awake()
{
overallDistance = 0;
lastDistance = 0;
timer = 0;
lastTime = 0;
speed = 0;
speed0 = 0;
firstTime = true;
allowTimer = true;
}
IEnumerator Start()
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser)
yield break;
// Start service before querying location
Input.location.Start(1, 1);
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
print("Timed out");
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
print("Unable to determine device location");
yield break;
}
else
{
// Access granted and location value could be retrieved
print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
longitude.text = Input.location.lastData.longitude.ToString();
latitude.text = Input.location.lastData.latitude.ToString();
lonA = Input.location.lastData.longitude;
latA = Input.location.lastData.latitude;
}
// Stop service if there is no need to query location updates continuously
//Input.location.Stop();
}
void Update()
{
longitude.text = Input.location.lastData.longitude.ToString();
latitude.text = Input.location.lastData.latitude.ToString();
timer += Time.deltaTime;
timerText.text = timer.ToString();
if (lonA != Input.location.lastData.longitude || latA != Input.location.lastData.latitude)
{
audio.Play();
CalculateDistances(lonA, latA, Input.location.lastData.longitude, Input.location.lastData.latitude); // last distance and overall distanceS
lonA = Input.location.lastData.longitude;
latA = Input.location.lastData.latitude;
lastTime = timer;
lastTimeText.text = lastTime.ToString();
timer = 0;
speed0 = speed;
speed0Text.text = speed0.ToString();
CalculateSpeed();
CalculateAcceleration();
}
}
public static float Radians(float x)
{
return x * Mathf.PI / 180;
}
public void CalculateDistances(float firstLon, float firstLat, float secondLon, float secondLat)
{
lonAText.text = firstLon.ToString();
latAText.text = firstLat.ToString();
lonBText.text = secondLon.ToString();
latBText.text = secondLat.ToString();
float dlon = Radians(secondLon - firstLon);
float dlat = Radians(secondLat - firstLat);
float distance = Mathf.Pow(Mathf.Sin(dlat / 2), 2) + Mathf.Cos(Radians(firstLat)) * Mathf.Cos(Radians(secondLat)) * Mathf.Pow(Mathf.Sin(dlon / 2), 2);
float c = 2 * Mathf.Atan2(Mathf.Sqrt(distance), Mathf.Sqrt(1 - distance));
lastDistance = 6371 * c * 1000;
result.text = lastDistance.ToString() + " meters";
overallDistance += lastDistance; // bu 1 anliq 6.000.000-dan boyuk qiymet ala biler
StartCoroutine(Overall());
}
IEnumerator Overall()
{
if (firstTime)
{
firstTime = false;
yield return new WaitForSeconds(2);
if (overallDistance > 6000000)
{
overallDistance = 0;
lastDistance = 0;
}
}
overallDistance += lastDistance;
overallResult.text = overallDistance.ToString() + " meters";
}
void CalculateSpeed()
{
speed = lastDistance / lastTime * 3.6f;
speedText.text = speed.ToString();
}
void CalculateAcceleration()
{
acceleration = (speed - speed0) / lastTime;
accelerationText.text = acceleration.ToString();
}
}
Thanks for any help and tip
PS. Please edit my question if I made any grammar and logical mistakeaccelerationlocationgpscalculationsspeedometerMon, 25 Apr 2016 07:11:21 GMTVagonnHow do I calculate custom font character texture uvs from .fnt file
http://answers.unity.com/questions/1146917/how-do-i-calculate-custom-font-character-texture-u.html
So i made a little .fnt file using shoebox and it was nothing else but a text file that contained some stuff about character positions/sizes on the image (in my case format of image is 186x189), and the main part of that .fnt file looks like this:
char id=65 x=93 y=26 width=16 height=25 xoffset=0 yoffset=55 xadvance=17 page=0 chnl=0 letter="A"
so the most important info that I get from that are x,y,width and height.
Like this:
![alt text][1]
[1]: /storage/temp/64571-fnt.png
And in the custom font index is the id and the there are 2 rects, one is Vert where I just add W = width and H = -height and after that one there is the Uv rect and I need a few formulas how to calculate those uvs from those x,y,width and height values from fnt file.
As far as I know values there are in range from 0 to 1 so to calculate x and w I just divided x and width by image width and that worked, but when I tried the same with y and h and divided them by image height I haven't got the correct uv values and instead of getting letter A i got... (part of the image that is... not 'a'), so what is the right formula to calculate those y and h values?uvsfontscalculationsWed, 24 Feb 2016 22:22:28 GMTado112