- Vector3 юнити не работает
- Re: Vector3.Reflect
- Re: Vector3.Reflect
- Re: Vector3.Reflect
- Re: Vector3.Reflect
- Re: Vector3.Reflect
- Re: Vector3.Reflect
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- Re: Vector3.Reflect (РЕШЕНО)
- В Unity, почему добавление Vector2 и Vector3 неоднозначно, но назначение не является?
- 2 ответа
- Ответ
- Анализ 1
- Анализ 2
- What is Unity Vector3? Unity Vector3 Detailed Guide – (2021)
- Unity Vector3 Mathematical Operations
- Codes That Can Be Used With Unity Vector3
- Unity Vector3 Properties-Accessible Variables
- Unity Vector3 Public Methods
- How to create a Vector3?
Vector3 юнити не работает
Serge 20 апр 2009, 17:45
Хотел сделать отскок сферы от стены, решил попробовать функцию Vector3.Reflect, по описанию вроде оно, но у меня почему-то не работает. Вернее работает как то странно. Подскажите плиз что я делаю не так? Мне нужно зеркальное отражение сферы от стены. Код простой.
Код: Выделить всё var originalObject : Transform;
var reflectedObject : Transform;
function Update () <
if (Input.GetKeyUp («space»)) <
reflectedObject.position = Vector3.Reflect (originalObject.position, Vector3.right);
>
>
originalObject — кубик в центре
reflectedObject — кубик рядом
Перед выполнением отр. кубик расположен впереди центрального, после выполнения его перемещает влево и в сторону. Позже выложу картинки.
Re: Vector3.Reflect
Neodrop 20 апр 2009, 17:59
Ну в справке, откуда вы скопировали этот код, ясно написано, что данный код (а именно Vector3.Right) отражает относительно мировой Z координаты. А вам нужно задать локальную, причём того объекта, от которого отражается ваш кубик.
Re: Vector3.Reflect
Serge 20 апр 2009, 18:19
Re: Vector3.Reflect
Neodrop 20 апр 2009, 18:27
Re: Vector3.Reflect
Serge 20 апр 2009, 19:08
Re: Vector3.Reflect
Neodrop 20 апр 2009, 19:19
Трудно. Ибо сам мокрый от окунаний.
Что то типа этого :
Код: Выделить всё function OnCollisionEnter(collision : Collision)
<
// Debug-draw all contact points and normals
for (var contact : ContactPoint in collision.contacts) <
Debug.DrawRay(contact.point, contact.normal, Color.white);
>
Re: Vector3.Reflect
Serge 21 апр 2009, 17:37
public class fizReflect : MonoBehaviour
<
Vector3 mVect ;
void FixedUpdate ( )
<
rigidbody . AddForce ( mVect ) ;
>
void OnCollisionEnter ( Collision collision )
<
ContactPoint contact = collision. contacts [ 0 ] ;
mVect = Vector3. Reflect ( mVect, contact. normal ) ;
>
>
Исправил скрипт. Заменил transform.Translate(mVect * Time.deltaTime) на rigidbody.AddForce(mVect). А то народ берет с ошибкой и не понимает почему не работает должным образом.
Re: Vector3.Reflect (РЕШЕНО)
Serge 16 янв 2010, 18:54
Сделал на основе данной функции демку. Нечто подобное пытался сделать еще на Virtools, но тогда так и не смог добиться нормального результата. Там в течение некоторого времени практически все шары неведомым образом покидали пространство куба в неизвестном направлении.
Здесь же, можете сами убедится, они никуда не пропадают и угол отражения считается правильно
Re: Vector3.Reflect (РЕШЕНО)
Neodrop 17 янв 2010, 06:19
Re: Vector3.Reflect (РЕШЕНО)
JenyaHW 18 янв 2010, 17:08
Re: Vector3.Reflect (РЕШЕНО)
Serge 18 янв 2010, 18:34
Re: Vector3.Reflect (РЕШЕНО)
JenyaHW 18 янв 2010, 23:31
Все-таки попробовал (тоже незавершенность) но отскок — правильный.
Re: Vector3.Reflect (РЕШЕНО)
Neodrop 18 янв 2010, 23:52
Re: Vector3.Reflect (РЕШЕНО)
JenyaHW 19 янв 2010, 09:52
Я понял почему у вас угол смотрелся нереалистичным вы использовали изменение координат.
а функция дает вектор скорости, поэтому нужно заменить на велосити. и убрать множитель дельтатайме, а сделать фикседапдейт, чтобы на всех компьютерах было одинаковая скорость (вернее не столько из за одинаковой скорости, сколько чтобы сэкономить производительность (все равно результат — тот-же)).
Re: Vector3.Reflect (РЕШЕНО)
Paul Siberdt 19 янв 2010, 10:23
Источник
В Unity, почему добавление Vector2 и Vector3 неоднозначно, но назначение не является?
Учитывая следующие два вектора:
Эта строка неоднозначна:
, в то время как это назначение не выполняется:
2 ответа
Сообщение о полной проблеме:
ошибка CS0121: вызов неоднозначен между следующими методами или свойствами: UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)’ and UnityEngine.Vector3.operator + (UnityEngine.Vector3, UnityEngine.Vector3)
Unity предоставил способ неявно преобразовать Vector3 в Vector2 и наоборот. Это вызывает двусмысленность в вашем случае, потому что могут применяться оба оператора +.
Настройте Vector2 на Vector3 явно в этой операции, так что компилятор знает, как использовать UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3) .
Если вам интересно, документы Microsoft для этой конкретной ошибки здесь .
Изменить после редактирования:
Vec3 += Vec2 является неоднозначным по той же причине, о которой говорилось выше. Представьте Vec3 += Vec2 на самом деле Vec3 = Vec3 + Vec2 . Vec3 + Vec2 может давать как Vector2 , так и Vector3 как ответ из-за неявных преобразований, поэтому вам нужно указать, что вы хотите.
Vec3 = Vec2 не является двусмысленным, поскольку Vec2 неявно преобразован в Vector3 , а затем назначается начальному Vec3. Таким образом, вся операция действительно Vector3 = Vector3 , без необходимости передавать Vec2 в код Vector3 вручную.
Позвольте мне переименовать vars (для ясности):
Ответ
Это из-за раздела pos3d + pos2d строки. Эта часть действительно неоднозначна, а += — нет. Позвольте мне пояснить, почему один и почему другой.
Анализ 1
компилятор сначала пытается оценить выражение pos3d + pos2d , прежде чем продолжить, независимо от того, где будет размещен результат.
Для этого система сначала пытается найти любую публичную статическую функцию, которая добавляет Vector3 плюс Vector2, например, эту возможную подпись:
или, например, эту возможную подпись:
Тем не менее, в API нет какой-либо из этих подписей, поэтому компилятор пытается «отличить» параметры от известных подписей.
Затем компилятор находит эти две потенциальные сигнатуры:
Итак, есть две возможности:
Так как оба литья возможны, pos2d может быть отброшен в Vector3, а pos3d — castabale в Vector2, тогда компилятор найдет возможные способы скомпилировать один и тот же исходный код (при условии, что будут созданы автоматические скрытые отливки).
Можно либо поместить pos3d в Vector2, либо продолжить вторую подпись, либо либо поместить pos2d в Vector3, либо продолжить первую подпись.
Как сначала оценивается выражение pos3d + pos2d , прежде чем принимать во внимание «где будет применен результат», тогда компилятор не знает что бы вы сделали — как кодер — как это выполнить.
Если вы хотите перейти в 3D, вы можете написать это:
и проблема исчезла, так как теперь ясно: сначала переместите pos2d в другой объект типа Vector3, затем сделайте сумму Vector3 + Vector3. При условии, что существует эта статическая подпись
, что он будет использоваться без какой-либо двусмысленности вообще.
Анализ 2
С другой стороны, когда вы делаете
нет двусмысленности: первая строка присваивает Vector3 в Vector3 (без сомнений).
Вторая строка эквивалентна
с особенностью transform.position оценивается только один раз, и поэтому этот тип учитывается, как вы можете видеть на этой странице Microsoft о += :
Кроме того, он говорит: «Оператор + = нельзя перегружать напрямую, но пользовательские типы могут перегружать оператор + (см. оператор)». поэтому мы должны подумать, что код Vector3 += , как описано в Microsoft, где говорится:
, за исключением того, что x оценивается только один раз. Значение оператора + зависит от типов x и y (добавление для числовых операндов, конкатенация для строковых операндов и т. д.).
, поэтому мы можем быть уверены, что второй подход вызывает операнд + класса Vector3 , который имеет подпись:
, поэтому нет другого способа добиться этого, чемпреобразование pos2d в Vector3 благодаря скрытому скрытому приложению, которое не может быть любой другой формы.
В Unity 5.0.1f1 Personal с помощью MonoDevelop-Unit 4.0.1 , как говорит Алекс М., строки:
по-прежнему выполняется ошибка «Assets/Scripts/CubeScript.cs(15,27): error CS0121: The call is ambiguous between the following methods or properties: ‘UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)’ and ‘UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)'»
, так что действительно + = использует обе подписи
, несмотря на то, что уже знает «где», результат должен быть помещен (я думаю, потому что вывод Vector2 может быть спрятан до места назначения (Vector3), и если этот прилив не был возможен, возможно, компилятор мог бы выбрать один с соответствующим типом вывода).
Источник
What is Unity Vector3? Unity Vector3 Detailed Guide – (2021)
By: Game Developer
What is Unity Vector3 in this article? I’ll answer his question and talk about the variable type Vector3, its usage areas, and the functions we can use. Vector3 is a type of variable that we can use on the Unity program, which contains 3 float-type variables called x,y,z that correspond to the axes in 3 dimensions, which we use to specify a vector size in short.
We often use this data type in positioning with Transform, changing direction, changing size, and especially when performing physics operations with the Rigidbody component. Only Vector2, which has a lot of common features and functions with a similar type of Vector2, but contains components for the X and y axes. As an example, a cube object that is on our Unity screen has a position value, and this is originally Vector3, and it describes the position of our cube between our game.
Or gravity affects our object with a Rigidbody component, and this quintessential velocity value changes and begins to fall. Gravity (gravity) here is a quç vector and describes the magnitude and direction of the acting force. In the same form, velocity is a velocity vector, describing the direction and magnitude of the velocity.
We moved forward by giving the names X to the horizontal and y to the vertical. You may not have seen the 3-dimensional at school, just if you were a little involved with Unity, it’s 3. you can also predict how the axis, the Z-axis, will work. Here is the Vector3 value, a structure that simply allows us to keep the value of each axis in a variable within itself and allows us to easily apply vector operations.
Now you have understood that these 3 variables I mentioned represent separate axes, I expect that after understanding this, I will now talk about mathematical operations for the Vector3 type. First, I should note that variables of type Vector3 can only add and subtract from each other. In multiplication and division operations, we can use other types in the form of int, float. Unity has different functions that it has provided, since I will only talk about using basic mathematics, I will leave this topic to the continuation of the article.
Unity Vector3 Mathematical Operations
In the genus Unity Vector3, the process of addition and subtraction is quite simple. Each digit actually processes the axis value with the axis value of the other vector. In other words, let’s define two variables such as a=(1,5,3) and B=(3,5,2), it is not defined in this way in encoding, by the way, I write in this way only for expression purposes. If we perform a-b, there will be a sequel (-2.0.1). We achieved this result by performing 1-3 on the X-axis, 5-5 on the Y-axis, and 3-2 on the most recent Z-axis.
But it may have caught your attention, and if we do a B-a, the result will not be the same. I’d like you to do B-a in your head now. Calm down, patience, the answer is coming. Yes, b-a=(2,0, -1) output. When we examine this position, the size of the vector we get will not differentiate the value of length (magnitude). But since the vectors indicate a direction, except for size, it can cause us to apply Q three in a very different direction, move. Of course, this is true in subtraction operations, a+b and B+a will always be equal to each other.
Codes That Can Be Used With Unity Vector3
We will learn about codes that can be used with Unity Vector3 under 3 headings. These headings are divided into properties-variables, public methods, and static methods similarly. Before going to these headings, let me talk about the first Vector3 class, the Constituent function of its type. In this way, let’s first learn how to create a vector variable.
//creates a new vector
// and x =1, y=3, z=5 value assignments.
Vector3 FirstVector=new Vector(1,3,5);
So we have provided a vector variable. Now, before I go to the subheadings, I will talk about some static properties, variables. These are actually variables that save us from writing vector values for quite a long time. First, I will explain it in bulk and immediately show its use in a single code blog.
- Back: Vector3(0,0,-1)
- Down: Vector3(0, -1, 0)
- Forward: Vector3(0, 0, 1)
- Left: Vector3(-1, 0, 0)
- NegativeInfinity: Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity)
- One: Vector3(1, 1, 1)
- PositiveInfinity: Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity)
- Right: Vector3(1, 0, 0)
- Up: Vector3(0, 1, 0)
- Zero: Vector3(0,0,0)
Unity Vector3 Properties-Accessible Variables
These properties are properties that are different for each Vector3 variable, contrary to what we first mentioned.
- magnitude: returns the size, length value of Vector3 in float.
- normalized: takes the Vector3 variable and calculates the component values x, y,z, even if the size of the vector is 1 unit. However, it changes the size of the vector, there is no change in its direction.
- sqrMagnitude: allows us to get the square of the length of the variable. it works faster than the magnitude feature. Because in the calculation steps of this length, the square of the first is obtained, then it takes more operations to get the square root of it and reach the length value.
- this [int]: allows us to access the value of the variable x,y,z with index values in a similar format as in the same arrays. it has an index value of x : 0, y: 1, and z: 2.
X: This allows us to get the value of the Vector on the X-axis.
Y: This allows us to get the value of the Vector on the Y-axis.
Z: This allows us to get the value of the Vector on the Z-axis.
void Start() <
Vector3 newVektor = new Vector3 (3, 4, 5);
Debug.Log(«Vector length: » + newVektor.magnitude);
Debug.Log(«Vector normalized: » + newVektor.normalized);
Debug.Log («Vector length squared: » + newVektor.sqrMagnitude);
Debug.Log («Vector values with index : x=» + newVektor[0] + » y=» + newVektor[1] + » z=» + newVektor[2]);
Debug.Log(«Vector x value: » + newVektor.x);
Debug.Log(«Vector y value: » + newVektor.y);
Debug.Log(«Vector z value: » + newVektor.z);
>
;
Unity Vector3 Public Methods
- Angle (): allows us to get the angle between the two given vector variables in the float type. The maximum value that this angle can take will be 180 degrees.
- ClampMagnitude (): creates a copy of the Vector variable based on the given length, keeping the direction the same, and this copy returns the value vector3 to us. In this way, we can maintain the direction and obtain a shorter vector size.
- Cross (): allows us to get a vector named cross product of the given two vectors, which is perpendicular to these two vectors. The order of variables is important, the result that will be obtained when their order changes will be in the opposite direction.
- Distance (): allows us to obtain the distance between two given Vector3 variables.
- dot (): this is a function that returns a number obtained by multiplying the size of the vectors by the cosine of the angle between them, which we can also use to understand whether two vectors are facing in the same direction.
- Lerp (): the lerp function is a function that also occurs in different mathematical variables, which allows us to get a value based on a certain ratio in two values. For example, with this function, we can move an object within the start and endpoints.
- LerpUnclamped (): lerpunclamped works similarly, only the relative value it can take can be greater than 1 or less than 0. In this way, we can go beyond the second variable.
- Max (): taking the largest values from the X,y,z components of the two vectors we give, creates a new Vector3 variable for us.
- Min (): taking the smallest values from the X,y,z components of the two vectors we V er creates a new Vector3 variable for us.
- movetowards (): this is the function where we give the start and endpoints and get us to move from start to finish step by step. It allows us to achieve a smoother and controlled movement.
- Normalize (): changes the components x,y,z so that the vector variable has a length of 1 unit. it changes on this variable, as opposed to the normalized property.
- OrthoNormalize (): normalizes the given vectors and makes them perpendicular to each other.
- Project (): allows us to get a projection of a vector onto another vector. We can also think of this as getting the shadow of an object falling to the ground.
- ProjectOnPlane (): works in the form of Project, it takes a normal vector value instead of just a second vector. It is normal, then is the vector that is exactly perpendicular to a surface.
- Reflect (): a Vector3 variable is a function that achieves its reflection using a normal axis in the form of a reflection that any identical object has in a mirror.
- RotateTowards (): allows us to switch from one vector to another in a smooth and controlled format, as in the same MoveTowards function.
- Scale (): allows us to multiply a variable of Type 2 Vector3. Here, the multiplication process is within each other of the components x,y,z.
How to create a Vector3?
Vector3(float x, float y, float z); //It is in the format.
Vector3 new_vektor = new Vector3(0.5f , 2.7f , 3.6f);
So we looked at what Vector3 is and the methods and variables that we can use with this variable type. Thank you for reading the article. For other Unity topics that might interest you, you can check it out right here: Unity 3D
Источник