Questions in topic: "calculation"
http://answers.unity.com/questions/topics/single/1298.html
The latest questions for the topic "calculation"How do you calculate the rotation of a hexagon based on the six Vector3 points
http://answers.unity.com/questions/1746136/how-do-you-calculate-the-rotation-of-a-hexagon-bas.html
I have given a hexagon with the position of its six vertices given. My question is, how to calculate the rotation of the hexagon in all three dimensions. If anyone could come up with a general function with these six vertices as arguments I would be soo thankful, because I by myself am not able to do that. I already tried it with Vector3.Angle, but I always got wrong results and now I gave up.rotationvector3anglecalculatecalculationSat, 27 Jun 2020 15:12:52 GMTstadlernicolas26Calculation error when multiplying a float
http://answers.unity.com/questions/1744158/calculation-error-when-multiplying-a-float.html
I am making a bank system and I found some issues about the interest calculation. If you try **Debug.Log(100000 * 1.05f - 100000);**, you will get a result 4999.992. Does everyone has idea how to solve this error?
Below are some of the wrong output:
Debug.Log(100000 * 1.05f - 100000); //Output: 4999.992
Debug.Log(100000 * 1.06f - 100000); //Output: 5999.992
Debug.Log(100000 * 1.07f - 100000); //Output: 7000.008calculationmultiplySun, 21 Jun 2020 08:22:46 GMTRexkwongdetermine that the spinning motion is "CW" or "CCW"
http://answers.unity.com/questions/1737473/determine-that-the-spinning-motion-is-cw-or-ccw.html
I have an object spinning on its axis how can I determine that the spinning motion is "CW" or "CCW".physicsdirectionvectorcalculationmathsTue, 02 Jun 2020 08:13:50 GMTmian_abdulTrouble calculating Arc offset position
http://answers.unity.com/questions/1675663/trouble-calculating-arc-offset-position.html
Hello everybody :)<br>
I am trying to create an angle arc, to help me visualize things better in the scene view. Unfortunately, I got myself stuck..
<br><br>
I use<br><br>
> Handles.DrawSolidArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius);
<br>to draw an arc using an angle I specify in the inspector.
<br><br>
Currently for **from** vector I use **transform.forward**, but it gives me this result:
<br><br>
![alt text][1]
<br>
How do I offset the vector to get this type of result instead?<br><br>
![alt text][2]
<br>
In this example angle is 90 degrees, but I can specify a different angle from 0 to 180 degrees and I would like if this arc would offset to the center as this is kind of a field of view of the object.<br><br>
I'm not the best when it comes to math, any help would be much appreciated! :)
<br><br>
void OnSceneGUI()
{
var objTransform = _reference.objectReferenceValue as Transform;
var center = new Vector3(objTransform.position.x, objTransform.position.y + 5, objTransform.position.z);
Handles.color = new Color(.5f, .5f, .5f, .25f);
Handles.DrawSolidDisc(center, Vector3.up, collider.radius);
Handles.DrawSolidArc(center, Vector3.up, objTransform.forward, _angle.floatValue, collider.radius);
Handles.color = Color.white;
}
[1]: /storage/temp/148263-ex1.png
[2]: /storage/temp/148264-ex2.pngvectormathfcalculationarcSat, 02 Nov 2019 19:00:54 GMTUserNobodyHow to calculate specific data before build and save it?
http://answers.unity.com/questions/1666948/how-to-calculate-specific-data-before-build-and-sa.html
Hi
I have about 1000 + objects in scene
according to the game logic - for each object I need to calculate mesh volume and axial length (max length of 3 lengths) and use later during specific situations in my game
but I'm confused - how to calculate it before build and also see it in inspector?
there is no problem to add script which will calculate volume and max axial lenght once scene is loaded. but in fact this data is not going to be changed, so there is no sence to calculate it each time I run the game. I would like to calculate it before building and save it. but confused how to make it
if I make script which calculate it during play - it will load CPU in vain
if I make editor script - it do not save data for build versionscripting problemeditorsave datacalculationSun, 22 Sep 2019 09:47:24 GMTalexulkinPlease help me to find a better way to calculate prices.
http://answers.unity.com/questions/1626091/please-help-me-to-find-a-better-way-to-calculate-p.html
I have a **panel with items**, a **list with added items** and a text where the **total price and mass** is shown.
The price for every object is written. I related the objects with Gameobjects elements in Unity and when one Gameobject is activated then another object (text with price) will be shown. However I can't write 1000 combinations this way if I have many objects. Is there a more clever solution? Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // Wichtig! Muss vorhanden sein!
public class Calculations : MonoBehaviour
{
public GameObject TextRumpfPrice, TextCabinPrice, TextMotorPrice;
private int rumpfprice = 10000;
private int cabinprice = 4000;
private int motorprice = 15000;
private int rumpfweight = 5000;
private int cabinweight = 2000;
private int motorweight = 1000;
private int totalprice1, totalprice2, totalprice3, totalprice4, zerototal;
private int totalweight1, totalweight2, totalweight3, totalweight4, zeroweight;
public Text TextTotalPrice1, TextTotalPrice2, TextTotalPrice3, TextTotalPrice4, TextZeroPrice;
public Text SSTextTotalPrice1, SSTextTotalPrice2, SSTextTotalPrice3, SSTextTotalPrice4, SSTextZeroPrice;
public Text SSTextTotalWeight1, SSTextTotalWeight2, SSTextTotalWeight3, SSTextTotalWeight4, SSTextZeroWeight;
public Text TextTotalWeight1, TextTotalWeight2, TextTotalWeight3, TextTotalWeight4, TextZeroWeight;
public Text TextCabinPrice1, TextRumpfPrice1, TextMotorPrice1;
public Text TextCabinWeight1, TextRumpfWeight1, TextMotorWeight1;
void Start()
{
}
void Update()
{
if(TextRumpfPrice.activeInHierarchy && !TextCabinPrice.activeInHierarchy && !TextMotorPrice.activeInHierarchy)
{
TextRumpfPrice1.text.ToString();
TextRumpfPrice1.text = rumpfprice.ToString("C2");
TextRumpfWeight1.text.ToString();
TextRumpfWeight1.text = rumpfweight.ToString();
}
if(TextCabinPrice.activeInHierarchy && !TextRumpfPrice.activeInHierarchy && !TextMotorPrice.activeInHierarchy)
{
TextCabinPrice1.text.ToString();
TextCabinPrice1.text = cabinprice.ToString("C2");
TextCabinWeight1.text.ToString();
TextCabinWeight1.text = cabinweight.ToString();
}
if(TextMotorPrice.activeInHierarchy && !TextRumpfPrice.activeInHierarchy && !TextCabinPrice.activeInHierarchy)
{
TextMotorPrice1.text.ToString();
TextMotorPrice1.text = motorprice.ToString("C2");
TextMotorWeight1.text.ToString();
TextMotorWeight1.text = motorweight.ToString();
}
if(TextRumpfPrice.activeInHierarchy && TextCabinPrice.activeInHierarchy && !TextMotorPrice.activeInHierarchy)
{
totalprice1 = rumpfprice + cabinprice;
TextTotalPrice1.text.ToString();
TextTotalPrice1.text = totalprice1.ToString("C2");
totalweight1 = rumpfweight + cabinweight;
TextTotalWeight1.text.ToString();
TextTotalWeight1.text = totalweight1.ToString();
}
if(TextRumpfPrice.activeInHierarchy && TextCabinPrice.activeInHierarchy && TextMotorPrice.activeInHierarchy)
{
totalprice2 = rumpfprice + cabinprice + motorprice;
TextTotalPrice2.text.ToString();
TextTotalPrice2.text = totalprice2.ToString("C2");
totalweight2 = rumpfweight + cabinweight + motorweight;
TextTotalWeight2.text.ToString();
TextTotalWeight2.text = totalweight2.ToString();
}
if(TextRumpfPrice.activeInHierarchy && TextMotorPrice.activeInHierarchy && !TextCabinPrice.activeInHierarchy)
{
totalprice3 = rumpfprice + motorprice;
TextTotalPrice3.text.ToString();
TextTotalPrice3.text = totalprice3.ToString("C2");
totalweight3 = rumpfweight + motorweight;
TextTotalWeight3.text.ToString();
TextTotalWeight3.text = totalweight3.ToString();
}
if(TextCabinPrice.activeInHierarchy && TextMotorPrice.activeInHierarchy && !TextRumpfPrice.activeInHierarchy)
{
totalprice4 = cabinprice + motorprice;
TextTotalPrice4.text.ToString();
TextTotalPrice4.text = totalprice4.ToString("C2");
totalweight4 = cabinweight + motorweight;
TextTotalWeight4.text.ToString();
TextTotalWeight4.text = totalweight4.ToString();
}
if(!TextCabinPrice.activeInHierarchy && !TextMotorPrice.activeInHierarchy && !TextRumpfPrice.activeInHierarchy)
{
totalprice2 = rumpfprice + cabinprice + motorprice;
zerototal = totalprice2 - (rumpfprice + cabinprice + motorprice);
TextZeroPrice.text.ToString();
TextZeroPrice.text = zerototal.ToString("C2");
totalweight2 = rumpfweight + cabinweight + motorweight;
zeroweight = totalweight2 - (rumpfweight + cabinweight + motorweight);
TextZeroWeight.text.ToString();
TextZeroWeight.text = zeroweight.ToString();
}
}
}c#calculationSat, 27 Apr 2019 10:53:28 GMTunity_BQtdjY5EUPsbTgHelp with arrival time calculations,Arrival time calculation?
http://answers.unity.com/questions/1591002/help-with-arrival-time-calculationsarrival-time-ca.html
So, i want to make an app that will calculate the time to the next arrival. I have a list of times for the arrivals, and i want to print the next arrival time.
Not sure how to do that, i have found (in system) DateTime, but it stores dates along with time. This would technically screw over my calculations, i just want the next arrival in minutes. Anyone that could assist?
sorry for bad formatting, i don't really know how to explain.calculationThu, 17 Jan 2019 04:19:40 GMTmr_awesomenessBounds.IntersectRay() inaccurate?
http://answers.unity.com/questions/1579490/raygetpoint-inaccurate.html
I am using Ray.GetPoint() in the simplest situation, and it's returning inaccurate information.
<br><br>
I'm intersecting a Ray with a Bounds. The Bounds is integer-aligned. The IntersectRay() method returns an exact value. But Ray.GetPoint() returns a value with error much greater than Mathf.Epsilon.
<br><br>
Example:
Bounds b = new Bounds(Vector3.one, Vector3.one * 2.0f);
Ray r = new Ray(new Vector3(0.5f, 0.5f, -3.7f), Vector3.forward);
float d;
b.IntersectRay(r, out d);
Vector3 p = r.GetPoint(d);
<br><br>
The point p should be (0.5, 0.5, 0). Instead, the Z value is off: "Ray: -3.700000E+000, Distance: 3.700000E+000, Point: -2.384186E-007"
<br><br>
If the Ray origin is integral, the result is as expected.
<br><br>
The particular ray is created by a camera which is itself at an integral point (in Z) in my test. But I want an accurate point on the surface of the bounding box, not one just outside of it.
<br><br>
I would like to work out the best way to adjust for the error.
<br><br>
One idea I have is to work out the face of the bounding box which the ray intersects. But I can't even check for the values of the point matching the min/max coordinates, because the error exceeds Epsilon.
<br><br>
Is there any solution besides a larger Epsilon? I can use something like 1E-006 I guess, although that's still a pretty large number, in general (although not in this case where I know I should have an integer value anyway).
<br><br>
UPDATE: I have done more careful analysis. The problem was not Ray.GetPoint(). It was Bounds.Raycast(). The distance value which seemed exact was actually a bit too small. I wrote a test and asserted that d == 3.7f, but instead:
Expected: 3.70000005f
But was: 3.69999981fraycastingcalculationMon, 10 Dec 2018 15:41:38 GMTbgulanowskiHow to calculate the areas of irregular shapes?
http://answers.unity.com/questions/1570915/how-to-calculate-the-areas-of-irregular-shapes.html
Hey,
I am pretty new to Unity and game development. I am trying to make a game where a player will draw lines and create some random irregular shapes. How can I calculate these irregular areas when the player draws a line? I am not sure how to approach this problem.
Currently, I am using line renderer to draw lines. So, I know where the lines begin and end. But, I don't know how to calculate the area automatically.
Can someone give me some directions?
![Sample Image][1]
[1]: /storage/temp/127588-pixil-frame-0-1.pnglineareacalculationSun, 11 Nov 2018 18:33:01 GMTmhmtnlrAngle between vectors - calculation
http://answers.unity.com/questions/1570639/angle-between-vectors-calculation.html
Hi everyone, i've created a script which gets me some strange values, hope someone can help me.
I want to calculate an angle between two Vector3's. One of them should only include the x-component of the object workplace (left picture), and the other one should be the resulting vector xy of the gameobject welding torch (right picture).
So I created the vectorWorkplace_x (see script) and the resultingVector_xyz (which I put in update because this object is movable) and calculated the angle.
As result I get values between approximately 18 - 24. Im pretty sure thats not the angle in degrees between these vectors.
So is this calculation correct? And how do I get the angle in degrees?
Thanks in advance! :)
![alt text][1]
Workplace / weldingTorch
![alt text][2]
[1]: /storage/temp/127539-2018-11-10-17-07-07-microsoft-visual-studio.png
[2]: /storage/temp/127540-gesamt.pngvector3anglecalculationuntiy3dSat, 10 Nov 2018 17:36:47 GMTJulian_SchCalculation errors?
http://answers.unity.com/questions/1558958/calculation-errors.html
I am coding a spring-mass dampener system in Unity and I am having trouble keeping a consistent oscillation. When the damping value is 0, the spring should oscillate indefinitely (while maintaining the same amplitude). All the formulas I am using are checked by a professor, so no issue there. But my spring keeps overshooting or undershooting the amplitude if I leave it running for a while. How can I fix this?
![alt text][1]
[1]: /storage/temp/125517-screen.pngphysics2dupdate functioncalculationinconsistentTue, 02 Oct 2018 20:56:24 GMTguitarmaniacfind the exact point on which a projectile will hit enemy
http://answers.unity.com/questions/1536516/find-the-exact-point-on-which-a-projectile-will-hi.html
Hey everybody.
I was just wondering if there is anyway to find the exact point on which a projectile will hit the enemy (head, lung, or other parts). In my game the enemies are far far away so the player has to aim above the enemy to hit him.
I,m using rigidbody and addforce for my projectile motion, and plus raycast is not possible as raycast move in straight line.
I want to find it as soon as the projectile is launch or even before it actually hit the enemy.
Thanks in advanceenemyprojectilehitcalculationmotion-trackingTue, 31 Jul 2018 13:45:52 GMTnotijazhow to cultivate the distance
http://answers.unity.com/questions/1533728/how-to-cultivate-the-distance.html
How to calculate the distance between 2 points and show it to the screencalculationWed, 25 Jul 2018 03:12:41 GMTwechat_os_Qy0_CfKzqWIIVem45Hkoy-cFkRotate an object's yaw, pitch, and roll relative to the Game Camera Axis.
http://answers.unity.com/questions/1531922/rotate-an-objects-yaw-pitch-and-roll-relative-to-t.html
Hi Everyone!
I'm currently trying to write a script to rotate an object relative to the camera's reference axis.
As of now in the script below, objects are rotated relative to themselves. I would like to change this, see below (this is a script attached to the gameobject to be rotated which references a control script and the camera transform).
void Rotate(float deg)
{
// Make sure the camera exists
var camera = GetCamera(Camera, gameObject);
if (camera != null)
{
int rotMode =obj.GetComponent<AssetControl>().RotationMode;
var axis = new Vector3(0, 0, 0);
if (rotMode == YAW) {
axis = new Vector3(0, 1, 0); //rotate about the y axis
} else if (rotMode == ROLL) {
axis = new Vector3(1, 0, 0); //rotate about the x axis
} else if (rotMode == PITCH) {
axis = new Vector3(0, 0, 1); //rotate about the z axis
}
transform.rotation *= Quaternion.AngleAxis(deg, axis); //do rotation
}
}
Ideally I would like to rotate the object relative to the camera orientation, i.e. if rotating by ROLL, rotate the the object about the axis pointing the the camera.x direction, rather than the x axis of the global world. In a nut shell, I'm trying to replace the game objects coordinate frame (x,y,z arrows), with the cameras coordinate frame, and rotate the about about itself. Basically there's no translation, and I'm not trying to rotate the object around the camera. I'm trying to rotate the object in place around the x,y, or z axis individual but with the reference of the camera's orientation (sorry for being redundant, I'm just trying to specify my problem in more detail).
Does anyone know how to do this? I tried to use the code below, but it did not work...
//get direction vector of camera to object and treat it as global axis of rotation
Vector3 dirVect = this.transform.position - camera.transform.position;
dirVect = Vector3.Scale(dirVect, new Vector3(1, 0, 1));
dirVect = dirVect.normalized; //dirVect now becomes direction of camera x axis?
I'd appreciate any help! Thank you for your time!!!rotationrotation axisscriptable objectcalculationrelative rotationFri, 20 Jul 2018 20:18:35 GMTunity_vJeO3Q91KqSEsgAngle between two Vectors split up into x,y,z components
http://answers.unity.com/questions/1528362/angle-between-two-vectors-split-up-into-xyz-compon.html
Hello,
I am developing an application for the HoloLens which is testing different aids to guide the users visual attention. The user finds himself in a environment with objects floating around him, where he has to find the next target object out of all the target objects.
What i want to do is calculate the angle between the main cameras forward (the direction the player is currentlylooking) and a target object the player has to look at next. I need to calculate this once before every target object. Then i want to track how much rotation the user is actually doing. I want those optimal and real angles split up into x,y,z components so I can compare the different guiding methods in respect to the axes.
My idea was to project the forward and target vector into the corresponding planes and then calculate the angle. As the user cant rotate himself around the x-axis, just move his head up and down, i nedd to correct for impossible x-axis angles. To do this I multiply the y component of the camera's forward by (-1) if the forward and target vector point in different quadrants. So for the initial rotation on the x-axis rotation i would do the following:
//calculate Vectors for target and camera forward
Vector3 targetDir = target.position - camera.position;
Vector3 forward = camera.forward;
//project the Vectors into the yz-plane and calculate the angle
Vector3 TargetProj = Vector3.ProjectOnPlane(targetDir, Vector3.right);
Vector3 ForwardProj = Vector3.ProjectOnPlane(forward, Vector3.right);
//compensate for impossible rotation maneuvers
if ((TargetProj.z < 0 && ForwardProj.z > 0) | (TargetProj.z > 0 && ForwardProj.z < 0))
{
ForwardProj.y = ForwardProj.y * (-1);
}
float angleX = Vector3.Angle(TargetProj, ForwardProj);
For the actual rotation the user is doing i would calculate the difference between updates on the cameras forward vector projected on the yz-plane:
void Update(){
float angleX;
Vector3 newForwardX = Vector3.ProjectOnPlane(forward_new, Vector3.right);
Vector3 oldForwardX = Vector3.ProjectOnPlane(forward_old, Vector3.right);
//compensate for impossible rotation maneuvers
if ((TargetProj.z < 0 && ForwardProj.z > 0) | (TargetProj.z > 0 && ForwardProj.z < 0))
{
ForwardProj.y = ForwardProj.y * (-1);
}
float angle_x = Vector3.Angle(newForwardX, oldForwardX);
angle_x = Mathf.Abs(angle_x);
angleX +=angle_x;
forward_old=forward_new;
}
In the following picture the blue line is the cameras forward, the yellow line is the target vector. The green objects form a tunnel, to guid the user to the next target. After clicking on the target, the next target is activated and i need to calculate the inital, optimal, rotation in x,y,z and record the actual rotation in x,y,z.
![alt text][1]
The problem is that when the user is moving his head to turn to the target and he isnt keeping his head level with the ground, the projection of vectors changes and the angle gets totally wrong.
Has anybody done something similar or can offer any help?
Thank you!
[1]: /storage/temp/120642-problem-angle.pngrotationanglesvectorscalculationThu, 12 Jul 2018 08:54:38 GMTBaconKnightProblem with calculating damage, value returning 0
http://answers.unity.com/questions/1459459/problem-with-calculating-damage-value-returning-0.html
Hello guys I was trying to calculating the damage that the player would receive although if defense value is different from 0 the result will always be 0, i know I must be missing something but i cant figure out why, can anyone help?
I've tried to round it , to cast it as either float and double but couldn't fix it.
Thanks in advance.
Code:
float healthToLose = (damage * (100 / (100 + defense)));
health -= (int)Mathf.Round(healthToLose);c#mathhealthdamagecalculationWed, 24 Jan 2018 20:10:04 GMTNemarquesRaycast distance change object color
http://answers.unity.com/questions/1414993/raycast-distance-change-object-color.html
Hi everyone, I wanted to get my player the object's color when he is near it, I'm new to scripting but I think it could be done with Raycasts: the smaller the distance, the stronger the player's color (as shown in the picture).
![alt text](http://answers.unity3d.com/storage/attachments/102988-concept.png)
I 'm learning how to cast a ray, but how can I implement the color variation in the script?
I have this piece of code, I wanted to cast the ray from the object that is going to change color but it seems that the raycast work only if the script is attached to the camera...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Raycasting : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (transform.position, fwd, out hit, 20.0F))
{
//I checked if the ray found my object
if (hit.collider.gameObject.name.Equals("object"))
print(hit.collider.gameObject.name);
}
}
}
P.s.
Is it possible to change hue when the player go near another object?
Thanks.raycastingcolor changecalculationMon, 02 Oct 2017 15:13:22 GMTEastAtomCalculations with users input
http://answers.unity.com/questions/1414698/calculations-with-users-input.html
I want to have two inpu fields and the user to give numbers on both. Then there's a Calculate button, that once pressed divides the former with the latter. How can I do that? I've tried some Googling around and got nowhere. And I'm using C#.c#inputfieldcalculationSun, 01 Oct 2017 20:05:11 GMTLeLaTe(long) type conversion is a bit inaccurate.
http://answers.unity.com/questions/1412533/long-type-conversion-is-a-bit-inaccurate.html
print((long)(0.0f * 10.0f));
print((long)(0.1f * 10.0f));
print((long)(0.2f * 10.0f));
print((long)(0.3f * 10.0f));
print((long)(0.4f * 10.0f));
print((long)(0.5f * 10.0f));
print((long)(0.6f * 10.0f));
print((long)(0.7f * 10.0f));
print((long)(0.8f * 10.0f));
print((long)(0.9f * 10.0f));
print("---------");
print((long)(1.0f * 10.0f));
print((long)(1.1f * 10.0f));
print((long)(1.2f * 10.0f));
print((long)(1.3f * 10.0f));
print((long)(1.4f * 10.0f));
print((long)(1.5f * 10.0f));
print((long)(1.6f * 10.0f));
print((long)(1.7f * 10.0f));
print((long)(1.8f * 10.0f));
print((long)(1.9f * 10.0f));
print((long)(2.0f * 10.0f));
![alt text][1]
Why are these results coming out? Do I miss something? I want to increase the number of floating-point and convert it to a (long) type, but the value is incorrect.
[1]: /storage/temp/102630-123.pngcalculationfloatingpointTue, 26 Sep 2017 20:50:19 GMTMun-Yeong-SeokLine renderer projectile trajectory in 3D world
http://answers.unity.com/questions/1409841/line-renderer-projectile-trajectory-in-3d-world.html
Hello,
I'm having a trouble with a script to calculate de ball trajectory of the cannons in my game.
I have a root object, inside him are the cannon mesh and a empty transform called point that I use for position and rotation when instantiate the ball on shoots.
I use a linerender on that point and a control script on the root to calculate the trajectory and shoot the cannon when needed.
My problem is the trajectory calculation, I already successful calculate it and it works fine, but it is a script that only 100% if my game was 2D, but the game is 3D.
So when I rotate the root in the Y axis the line renderer rotates too, but its not in the right location anymore, some codes tests make it off-set from the point's origin and other makes the curvature of the parabola changes too without changing the power of the shoot and not the right forward from point.
The actual code:
Vector3 vel = point.forward * power;
//Vector3 vel = point.TransformDirection(new Vector3(0, 0, power));
Vector3 pVelocity = vel / 1;
float velocity = Mathf.Sqrt((pVelocity.y * pVelocity.y) + (pVelocity.z * pVelocity.z));
float angle = Mathf.Atan2(pVelocity.y, pVelocity.z);
float fTime = 0;
lineRenDebug.positionCount = numOfTrajectoryPoints;
for (int i = 0; i < numOfTrajectoryPoints; i++) {
float dx = velocity * fTime * Mathf.Cos(angle);
float dy = velocity * fTime * Mathf.Sin(angle) - (Physics2D.gravity.magnitude * fTime * fTime / 2.0f);
Vector3 pos = new Vector3(0, dy, dx);
//Vector3 pos = new Vector3(transPonta.position.x, dy, dx);
//Vector3 finalPos = Vector3.Scale(point.forward, pos) + point.position;
//Vector3 finalPos = point.TransformDirection(point.position + pos);
Vector3 finalPos = point.position + pos;
lineRenDebug.SetPosition(i, finalPos);
fTime += 0.15f;
if (finalPos.y < -2f) {
lineRenDebug.positionCount = i;
break;
}
}
The comments are some changes that I tried and not worked.
Someone can try to help me? Or a tip that something that I'm missing here.
Thanks.linerenderermathfcalculationprojectilesWed, 20 Sep 2017 19:42:28 GMTAisenheinDamage gets multiplied for some reason.
http://answers.unity.com/questions/1408091/damage-gets-multiplied-for-some-reason.html
So I made a collision damage script but for some reason the variables get multiplied but
it works fine if I stand at certain angles.
Script for enemy projectiles. It sometimes multiplies x2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ebulletdamage : MonoBehaviour {
public float damage = -10;
public float lifetime = 0.5f;
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Player")
{
other.gameObject.GetComponent<playerhealth>().ChangeHealth(damage);
Destroy(gameObject);
}
}
void Update()
{
Destroy(gameObject, lifetime);
}
}
Player health:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerhealth : MonoBehaviour
{
public float maxHealth = 100f;
public float curHealth = 100f;
void start()
{
}
void Update()
{
}
public void ChangeHealth(float PAmount)
{
curHealth += PAmount;
}
}
Medkit. It gets multiplied x4:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class medkit : MonoBehaviour {
public float heal = 10;
// Use this for initialization
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Player")
{
other.gameObject.GetComponent<playerhealth>().ChangeHealth(heal);
Destroy(gameObject);
}
}
}collisiondamagecalculationSat, 16 Sep 2017 20:54:31 GMTunity_q3nZ52RXZ2UP2gQuaternion using global values instead of local. Please help :(
http://answers.unity.com/questions/1383860/quaternion-using-global-values-instead-of-local-pl.html
Hi, I am trying to have the turret rotate to where it should for the bullet to be fired correctly at the target. In this script I have it calculate what angle the bullet should be fired at. That part works perfectly. However, whenever this rotates the turret, it seems to use the global rotation instead of the local. Please note this script is attached to a parent object of the turret being rotated. What am I doing wrong? I used Debug.Log to determine that the turretRot variable is giving 270 degrees extra in the Y value because of the global rotation. I really am struggling with this and have been for a while, I would be thankful for any help at all. Thank you all. :)
EDIT: Would it just be easier (and less CPU intensive) to use a Bezier curve with different points, and have the bullet use a simple MoveTowards function to go to each point? I already have this set up I just thought this way that I am trying would look better and be more optimized. Is this true?
public class AngleCalculator : MonoBehaviour {
[SerializeField]
Transform cannonBase;
[SerializeField]
Transform turret;
[SerializeField]
Transform firePoint;
[SerializeField]
GameObject projectilePrefab;
[SerializeField]
float cooldown = 1;
private float currentSpeed;
private float currentAngle;
private float lastShotTime;
public float turnSpeed;
public float shootDelay;
private bool isTarget;
private Quaternion lookRotation;
public Transform currentTarget;
private float turretAng;
public void SetTargetWithSpeed(Vector3 point, float speed, bool useLowAngle)
{
currentSpeed = speed;
Vector3 direction = point - firePoint.position;
float yOffset = direction.y;
direction = direction - (Vector3.Dot(direction, Vector3.up) * Vector3.up);
float distance = direction.magnitude;
float angle0, angle1;
bool targetInRange = LaunchAngle(speed, distance, yOffset, Physics.gravity.magnitude, out angle0, out angle1);
if (targetInRange)
currentAngle = angle0;
//currentAngle = useLowAngle ? angle1 : angle0;
SetTurret(direction, currentAngle * Mathf.Rad2Deg);
}
public void Fire()
{
GameObject p = Instantiate(projectilePrefab, firePoint.position, Quaternion.identity);
p.GetComponent<Rigidbody>().velocity = turret.forward * currentSpeed;
lastShotTime = Time.time;
}
//
private void SetTurret(Vector3 dir, float turretAngle)
{
isTarget = true;
lookRotation = Quaternion.LookRotation(dir);
turretAng = turretAngle;
}
// Update is called once per frame
void FixedUpdate () {
//SetTargetWithSpeed(target.transform.position, initialFireSpeed, useLowAngle);
if(isTarget == true)
{
Vector3 turretRot = new Vector3(-turretAng, lookRotation.eulerAngles.y, lookRotation.eulerAngles.z);
Debug.Log(turretRot);
Vector3 rotation = Vector3.MoveTowards(cannonBase.rotation.eulerAngles, lookRotation.eulerAngles, Time.deltaTime * turnSpeed);
Vector3 rotation2 = Vector3.MoveTowards(turret.rotation.eulerAngles, turretRot, Time.deltaTime * turnSpeed);
cannonBase.rotation = Quaternion.Euler(0f, rotation.y, 0f);
turret.rotation = Quaternion.Euler(rotation2.x, rotation2.y, 0f);
}
else if(currentTarget == null && !isTarget)
{
isTarget = false;
}
}
public void CalculateAngle(Transform target, float initialFireSpeed, bool useLowAngle)
{
SetTargetWithSpeed(target.position, initialFireSpeed, useLowAngle);
currentTarget = target;
StartCoroutine(WaitFire());
}
public IEnumerator WaitFire()
{
yield return new WaitForSeconds(shootDelay);
Fire();
}
/// <summary>
/// Calculates the two possible initial angles that could be used to fire a projectile at the supplied
/// speed to travel the desired distance
/// </summary>
/// <param name="speed">Initial speed of the projectile</param>
/// <param name="distance">Distance along the horizontal axis the projectile will travel</param>
/// <param name="yOffset">Elevation of the target with respect to the initial fire position</param>
/// <param name="gravity">Downward acceleration in m/s^2</param>
/// <param name="angle0"></param>
/// <param name="angle1"></param>
/// <returns>False if the target is out of range</returns>
private bool LaunchAngle(float speed, float distance, float yOffset, float gravity, out float angle0, out float angle1)
{
angle0 = angle1 = 0;
float speedSquared = speed * speed;
float operandA = Mathf.Pow(speed, 4);
float operandB = gravity * (gravity * (distance * distance) + (2 * yOffset * speedSquared));
// Target is not in range
if (operandB > operandA)
return false;
float root = Mathf.Sqrt(operandA - operandB);
//High Angle
angle0 = Mathf.Atan((speedSquared + root) / (gravity * distance));
//Low Angle
angle1 = Mathf.Atan((speedSquared - root) / (gravity * distance));
return true;
}
}rotationquaternionmathglobalcalculationMon, 24 Jul 2017 20:04:49 GMTYoshinator2Math Genius NEEDED! Algorithm problem with parabola
http://answers.unity.com/questions/1382704/math-genius-needed-algorithm-problem-with-parabola.html
Hi all, I am trying to make a targeting system with an artillery turret in which there is a set distance, velocity, and gravity acceleration. This targeting system is supposed to calculate the angle in which the turret should fire at to hit the target. I am having some trouble as it is either undershooting or overshooting the target, and am wondering if I have the ratios of real world values like Unity velocity to Real World velocity mixed up or if the equation is wrong. Here is my code:
public class test : MonoBehaviour {
public float angle;
public float g = Physics.gravity.y;
public float v = 1f;
public float d;
public Transform firePoint;
public Transform target;
public TestAAT3 obj;
// Use this for initialization
void Start () {
obj = FindObjectOfType<TestAAT3>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Alpha1))
{
CalculateAngle();
}
}
//d = distance between firepoint and target
//g = gravitational acceleration
//v = given velocity
//angle = theta
public void CalculateAngle()
{
d = Vector3.Distance(firePoint.position, target.position);
angle = (1/2) * Mathf.Asin((g * d) / (Mathf.Pow(v_, 2)));
Debug.Log(d);
obj.Fire(d);
}
}
Any and ALL help is appreciated. I've looked at wikipedia, khan academy videos, etc. Nothing helps!mathanglealgorithmcalculationparabolaSat, 22 Jul 2017 06:09:23 GMTYoshinator2Rotate camera around object and let it centered
http://answers.unity.com/questions/1364621/rotate-camera-around-object-and-let-it-centered.html
Hi,
I have a scene where I have a game board (just like a chess board but with any possible Width x Height). My camera is child of a camera target empty object because I want to be able to move the camera completely independently the flipping angle I'm giving the camera around the local X axis (just like someone with a selfie stick looking up or down). The problem I have is when I'm no longer in top view (Flipping angle == 0 degree), the board is obviously no longer centered in the screen (because of the perspective). How can I manually find the middle point of the board (with the perspective taken into account) as well as finding the distance the camera should be from that middle point to see the complete board with some kind of padding ?
I know the formula to know how far the camera needs to be to view a specific frustum size (width and height), so to find the middle point or the board in perspective, it's probably just a matter of projecting the board to a plane parallel to the frustum, measure the corresponding trapezoid, divide in half, took the middle point and ray casting back to a plane with Vector3.up as the normal.
I know I could use Camera methods like WorldToScreenPoint to project the corners of my board on the frustum and then adjust accordingly but I would like to calculate it directly and have some functions I could use without moving the real camera (in order to move it smoothly with lerp functions). The 2 methods I'm trying to write are
Vector3 FindMiddleBoard(float cameraFlippingAnglesAroundX, int boardWidth, int boardHeight)
float FindFrustumHeightNeededToDisplayEntireBoard(int boardWidth, int boardHeight)
It's probably easier than I think, but I'm lost in all those maths.
F.Y.I. the method I'm using to get the frustum size needed to display my board is:
float FindCameraDistanceNeeded(int boardWidth, int boardHeight, int padding, float cameraAspect, float cameraFieldOfView)
{
float result = 0.0f;
var widthFromFrustumHeight = (boardWidth + padding) / cameraAspect;
var maxFrustumHeight = Mathf.Max(widthFromFrustumHeight, (boardHeight + padding));
result = (maxFrustumHeight * 0.5f) / Mathf.Tan (cameraFieldOfView * 0.5f * Mathf.Deg2Rad);
return (result);
}
Thanksscripting problemcamera-movementcamerascamera rotationcalculationMon, 12 Jun 2017 17:09:16 GMTYoGoUrTcvCalcOpticalFlowPyrLK function of openCV
http://answers.unity.com/questions/1361555/cvcalcopticalflowpyrlk-function-of-opencv.html
(first, sorry for my bad English!)
Hello! I'm a student studying unity.
My question :
Is it possible to make it similar to the cvCalcOpticalFlowPyrLK function of openCV using WebCamTexture??
I can't even catch it. please help me? :-C
thank you!androidunity5functionhow tocalculationSun, 04 Jun 2017 07:56:44 GMTElizabeth_00Is it possible to use face normals as vertex normals in procedurally generated meshes?
http://answers.unity.com/questions/1350302/is-it-possible-to-use-face-normals-as-vertex-norma.html
Hi All,
I have a problem with getting the normals right on a procedurally generated mesh in my project.
I will attempt to clarify the steps I am following:
- I have a 3dCAD model (.ifc file) of a building that i parse using an external library (xBIM) and obtain the vertice of the mesh and the triangle indices array (mesh. vertices and mesh. triangles)
- Let's say that I have a wall with 6 faces (cuboid). When I parse the triangulation of this wall, I obtain 8 vertices and the 3 triangle vertices per triangle per face (i.e 2 triangles per face * 6 faces = 12 triangles. 3 vertices per triangle and hence 12*3 = 36 indices)
- I use these as the arrays as mesh.vertices ( Vector3 , length 8) and mesh.triangles (int[], length36)
- At this point I get the mesh right in Unity (the geomertry is correctly replicated), but the shading is bad and the edges of the shape are not visible.
- Unfortunately, the library I am using gives the face normals instead of the vertex normals. Which means that per geometry (of 6 faces) I get a normal array of 6 members.
- How do I use these normals to assign the normals to vertices so as to have a correctly displayed mesh in Unity?
Currently I am using the triangles array to compile an elaborate vertices array (using the 8 vertex points in an ordered manner of 36 points to define the 6 vertices that define each of the 6 faces of the cuboid), something similar to the what is done **[here][1]** .
Therfore, my vertices array is now 36 * Vector3 members long. In an attempt to assign normals to these vertices, I used the face normal I obtained and then assigned the same normal to all the vertices that are deining that face.
For e.g, vertices 0,1,2,1,0,3 define the 2 triangles of the front face of the cuboid. I used the face normal obtained for this face and assigned that as the normal vector for each of the vertex.
Anyway, I get a strange result and the front faces of the geometries are culled.
The issue is the same even if I use mesh.RecalculateNormals() method instead of assigning the normals at all to the mesh.
Is there something I am missing/ doing wrong in assigning the normals/vertices that the mesh is incorrectly rendered? Btw, I also tried reversing the order of mesh.trianglesa array, but the result was same.
Please help. I apologize for the verbose question, but I hope it explains my problem.
![alt text][2]
The mesh hhighlighted is invisible but the geometry is alright when viewed from the opposite side.
![alt text][3]
The front faces of these cuboid (wall) geometries are culled.
The part of code I am using to assign the mesh data is as follows. The vertices and triangles arrays are parsed from an XML file:
GO.AddComponent<MeshFilter>();
GO.AddComponent<MeshRenderer>();
Mesh mesh = GO.GetComponent<MeshFilter>().mesh;
mesh.Clear();
Vector3[] mod_Verts = new Vector3[meshTriangles.Count];
//meshtriangles.count is 36 // meshtriangles is the list of indices used as mesh.triangles
int[] mod_Triangles = new int [meshTriangles.Count];
for (int x = 0; x < mod_Verts.Length; ++x)
{
mod_Verts[x] = meshVertices[meshTriangles[x]]; // extends vertices array to define vertices
for each face
Debug.Log(GO.name + "_"+ x + "_" + mod_Verts[x] + " | " + " Vert_No: " +
meshTriangles[x]);
mod_Triangles[x] = x;
}
mesh.vertices = mod_Verts;
mesh.triangles = mod_Triangles;
mesh.RecalculateBounds();
//mesh.normals = meshnormals.ToArray();
mesh.RecalculateNormals();
[1]: http://wiki.unity3d.com/index.php/ProceduralPrimitives#C.23_-_Box
[2]: /storage/temp/93660-1.png
[3]: /storage/temp/93661-2.png
Many thanks in Advance,
Animeshnormalsprocedural meshcalculationSun, 07 May 2017 21:29:54 GMTanirudhnacalculate what angle should the turret fire with a rigibody bullet [C#]
http://answers.unity.com/questions/1341882/calculate-what-angle-should-the-turret-fire-with-a.html
I got 3 variable bullet drag, bullet speed, and the distance between the target end the turret. i want the function return the angle should the turret aim at.c#unity 5rigidbodyfunctioncalculationWed, 19 Apr 2017 13:23:01 GMTCeliswenMouseOrbitImproved camera distance seemingly inverted
http://answers.unity.com/questions/1307669/mouseorbitimproved-camera-distance-seemingly-inver.html
I'm currently working on a game prototype where the camera is controlled by the commonly used **MouseOrbitImproved** script, however I've run into a problem concerning the camera's distance to the player when the player is approaching a surface.
It would seem that the calculation for the collision distance is inverted, I'll explain.
When the camera is in-between the player and a wall,
wall|__[camera]---------(player)
if the player moves towards the wall, the moment the wall comes within the same distance as the camera, the camera zooms in on the player.
wall|_______ [camera]-(player)
However, the closer the player gets to the wall, the further away from the player the camera positions itself.
wall|__[camera]----(player)
This leads to the camera clipping through walls and other geometry where it is undesired.
[camera]--wall|(player)
If this isn't clear please ask more questions.
The **MouseOrbitImproved C#** code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour
{
public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
//public float distanceMin = .5f;
//public float distanceMax = 15f;
private Rigidbody rigidbody;
float x = 0.0f;
float y = 0.0f;
// Use this for initialization
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
rigidbody = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (rigidbody != null)
{
rigidbody.freezeRotation = true;
}
}
void LateUpdate()
{
if (target)
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
//distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
float dst = distance;
RaycastHit hit;
if (Physics.Linecast(target.position, rotation * new Vector3(0f, 0f, -distance) + target.position, out hit))
{
dst -= hit.distance;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -dst);
Vector3 position = rotation * negDistance + target.position;
// where the problem likely occurs
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}
What i'm looking for is a possible solution or help to pinpoint the problem in this code.cameracollisioncamera-movementclippingcalculationThu, 02 Feb 2017 15:13:20 GMTYrjanaLooking for help with orbit/follow player script vector math calculations
http://answers.unity.com/questions/1297326/looking-for-help-with-orbitfollow-player-script-ve.html
So basically I have an object, a 3D menu, attach itself to a game object when that object is selected. The camera is a first person camera (actually this is for a HoloLens app), so the player can walk around the object and look at it from any angle and I want the 3D menu to move around the object following the player at a particular distance (toward the player) from the root of the object the menu is attached to. The menu is circular so the player can see the menu options around the edge but still see the object as if looking through a scope.
I'm fairly new to Unity and vector math, so I'm having trouble figuring this out the basic calculations that are needed. I am already using a billboard script attached to the circular menu so that it constantly faces the player. I just can't get it to move in orbit like fashion following the player (Camera.main) position at a set distance from the object.
Note: The menu will appear when the player clicks on the object, but so that the user doesn't forget to close the menu, it will disappear if the player moves away from the object.
Sorry I don't really have any code. Basically I just have the game object called ObjectOfMenu.
(This is a first every post/request for help. I defiantly need to learn quite a bit about vector math.)vector3directionfolloworbitcalculationWed, 11 Jan 2017 01:21:23 GMTJasonsFreeTimeCalculation Error, please send help.
http://answers.unity.com/questions/1295396/a-few-issues.html
Hi! So, I'm working on a game in Unity and I am running in to a few issues. I have narrowed this down to error on my end, but I'm not sure what exactly it is. What I'm working on is 2D, block - based terrain, and I am currently doing terrain editing. The problem is, I can't seem to edit blocks if either the X or Y coordinate is below zero. Here's my code:
<code>
Vector2 pos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 cPos = new Vector2(((int)pos.x / World.chunkSize) * World.chunkSize, ((int)pos.y / World.chunkSize) * World.chunkSize);
Debug.Log(cPos);
pos.x += 0.5f;
pos.y += 0.5f;
Chunk c = Chunk.GetChunkAt((int)cPos.x, (int)cPos.y);
if(c != null)
{
c.RemoveBlock((int)(pos.x - cPos.x), (int)(pos.y - cPos.y));
}
</code>
So basically, I round the mouse position to a Chunk position in world coordinates. Then, I get that chunk and remove the specified block. I have the 'remove block' method to just return if either X or Y is less than zero, X or Y is greater than the chunk size. Otherwise, remove the specified block.
Here's my GetChunk code:
<code>
public static Chunk GetChunkAt(int x, int y)
{
foreach(Chunk c in allChunks)
{
if(c.transform.position.x == x && c.transform.position.y == y)
return c;
}
return null;
}
</code>
And my RemoveBlock code:
<code>
public void RemoveBlock(int x, int y)
{
if(x < 0 || y < 0 || x >= World.chunkSize || y >= World.chunkSize)
return;
map[x,y] = 0;
for(int i = 0; i < transform.childCount; i++)
{
if(transform.GetChild(i).transform.position == new Vector3(x,y,0) + this.transform.position && transform.GetChild(i).GetComponent<SpriteRenderer>().sortingOrder == 1){
Destroy(transform.GetChild(i).gameObject);
return;
}
}
}
</code>errorcalculationSat, 07 Jan 2017 00:47:03 GMTKurdle_4855