I'm new in Unity and I'm working on a simple project but I'm stuck.
So my idea is when the player touches the bottom side of a ball it goes the opposite direction. Pretty much like in real life, if you kick a ball on the bottom side it will go up, but in 2D version.
I tried finding the opposite point of where the player touched the ball and making a vector by subtracting the original point and the opposite point, and then applying force to move the ball but it doesn't work.
void MoveBall()
{
x = mouseClickPosition.x;
y = mouseClickPosition.y;
oppositeClickPosition.x = -x;
oppositeClickPosition.y = -y;
Vector2 direction = oppositeClickPosition - mouseClickPosition;
rb.AddForce(direction * force, ForceMode.Impulse);
}
You have to subtract the mousePosition and the center of the ball.
Vector3 clickedPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 ballCenter = ballTransform.position;
// If this goes the opposite direction just swap the values.
Vector3 forceDirection = (ballCenter - clickedPosition).normalized;
ballRigidbody.AddForce (forceDirection * strength, ForceMode.Impulse);
This way you find the direction and add the force you want, you can not use the normalized Vector3 if you want to use the distance as a factor too.
And you can catch that event properly on OnMouseDown if the ball has a collider
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
This may be helpful:
https://answers.unity.com/questions/681698/vector-between-two-objects.html
It Explains how to do it in 3D but the idea applies to both.
In your case, instead of oppositeClickPosition you should use the position of the ball:
Vector2 direction = transform.position - mouseClickPosition;
(replace transform.position with the position of the ball if this script is not attatched to the ball)
Hope that helps!
Related
I'm trying to make the camera rotate around an object according to the movement of the mouse, and this is what I've come up with:
void Start()
{
direction = new Vector3(1f,0f,0);
direction.Normalize();
Debug.Log(direction);
mousePosCurr = Input.mousePosition;
}
void Update()
{
mousePosPrev = mousePosCurr;
mousePosCurr = Input.mousePosition;
mouseVector = (mousePosCurr - mousePosPrev);
mouseVector = mouseVector * sensitivity;
direction = Quaternion.Euler(mouseVector.y, mouseVector.x, 0) * direction;
direction.Normalize();
Debug.Log(direction);
this.transform.position = (target.position + tOffset + (direction * distance));
transform.LookAt(target.position + tOffset, Vector3.up);
}
Now, I'm sure that there are at least a million problems with this code, however the main one I'm facing right now is that the x rotation does not work correctly, unless the y rotation is in a specific direction.
What's happening is basically that the more I rotate in the y axis the more "inprecise" the x movement becomes. So for example, when the camera is south of the object I'm rotating it around, the x rotation works exactly as it should, you move the mouse up, and the camera points up and viceversa, but when it's west of it the movement of the mouse required for the vertical rotation is no longer vertical, but diagonal, and when it's north of the object the movement is inverted: moving the mouse up makes the camera point down and viceversa.
This seems most likely caused by the fact that regardless of the horizontal rotation of the direction vector, I'm still rotating along the x axis in the same direction, as if the camera was south of the object.
However, even having (hopefully) identified the problem, I'm still clueless as to how to solve it, so I'm asking for help here.
Note: I just noticed that I probably used the term "rotation" wrong in this post. When I write "rotation of the camera", I'm actually referring to the rotation of the "direction" vector.
alright so I am not the best in Unity so this might be completely useless but when I try to rotate my camera around an object I create an empty game Object and make the camera a child of it, like this
so that I can just just rotate the Game Object to rotate the camera around a fixed point maybe your code will work
I have a ball object in Unity 2D, this ball spawns at random positions on the screen and I want it to move in a 'straight-line depending on its direction e.g. if it's from the left it goes to the right or if it's from the top it goes to the bottom. I'm not sure if I should use transform.position/addforce/velocity to accomplish this and what direction I should use.
The following are what I have tried so far (I've tried using all directions)
ballRigidBody.AddForce(transform.up * speed);
ballRigidBody.velocity = Vector2.up * speed;
transform.position+=Vector2.up;
In Unity3D transform.forward is the go to variable when you want to move forward.
In Unity2D transform.right is the standard.
You can move your ball to its right with this code:
void Update()
{
GetComponent<Rigidbody2D>().velocity = transform.right * speed;
}
If you run this code the ball will always move into the direction of the red arrow.
You can see the arrows by selecting the move tool on the top left and then clicking on your ball inside the editor.
If you want to have your ball to always follow the green arrow you have to use transform.up.
transform.right and transform.up are both used relative to your object.
That means by changing the z rotation of your object you can modify the direction it should go in.
You can try out the following code to see your ball move to its right and rotate slowly on its z axis. This will cause the ball to move in a circle since it is still following the red arrow.
void Update()
{
GetComponent<Rigidbody2D>().velocity = transform.right * speed;
float speedRotate = 100;
transform.Rotate(Vector3.forward * speedRotate * Time.deltaTime);
}
When you always want to move an object to the right, no matter the rotation, you use Vector3.right instead of transform.right.
From your other comments I understand that you want your ball to always face into the direction in the middle of the screen. You can just rotate it to the middle of the screen when it spawns by using this code:
void Start()
{
transform.right = new Vector3(0, 0, 0) - transform.position;
}
This will get the ball to face the 0,0,0 position inside of your world. If 0,0,0 is in the middle of your screen it will face that direction. Otherwise you have to find out which coordinate your middle of your screen has.
I'm not sure what you're asking, but you can do ballRigidbody.velocity = transform.foward*speed, to make it go in the current direction it is facing.
If you want a ball you spawn on the left side of the screen to move to the right only, then set velocity like rb.velocity = Vector3.right * speed, and so on with each direction.
In this case, you should first check which position the ball spawned at (Top, Bottom, Left, Right), then from that decide the movement direction. If the ball spawns at the bottom, the direction to go up should be Vector3.up for example.
After you get the force, you can use rigidBody.AddForce(direction * speed); to move the ball.
I have a 2d arrow rotating to always face the a target (the target in this case is the cursor), the pivot is my player character. I need to restrict this arrow to only follow the target if it is inside an angle of the player, an example would be 90 degrees, so it would only follow if the cursor is in the top right part of the screen.
I have worked with vector directions and methods such as Vector2D.angle, but they all seem to have some restriction i can't workaround, Vector2D.angles restriction is that the 3rd position it uses to calculate the angle is the world center(0, 0), my player is mobile so that doesn't work.
So i think what im asking is if theres a way to store an angle, and then check if something is within that.
Here is the code i use for rotating my arrow, theres more to the script but i removed the unnecesary parts:
public float speed;
public Transform target;
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = target.position - transform.position;
target.position = mousePosition;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
Sorry if this is formatted poorly, its my first time posting here, thank you a million times if you are able to help me, i have been stuck on this for days.
Was asked to clarify question so here is an attempt:
This picture shows an example of what i mean, the arrow is rotating around the center of the circle, (it is rotating so it always points towards my cursor). What i need is a way to restrict it so it only points towards the cursor if it is within a specific angle (red lines in picture), that's what im having trouble with. I can't find a way to store this threshold and i can't seem to find a way to compare the cursors direction with it.
I think it would be possible if it was possible to choose a custom center for Vector2D.angle, but that doesn't seem to be the case.
I hope this clarifies what my question, i may just very well be stupid and overlooking something obvious but i really can't find a way to make this possible.
thanks again.
Important fields/inputs
First, we need to know the boundary directions in world space:
public Vector2 boundaryDirectionLeft;
public Vector2 boundaryDirectionRight;
The important piece is that the angle made clockwise from boundaryDirectionLeft to boundaryDirectionRight is the region the arrow shall remain inside. In the case of your image, boundaryDirectionLeft could be Vector2.up and boundaryDirectionRight could be something like new Vector2(1f,-1f).
We also need to know which local direction the arrow is facing before any rotation is applied. E.g., if the arrow is always pointing with the local red arrow axis (the local right direction), this would be Vector2.right:
public Vector2 localArrowDirection;
And lastly, we need a top speed for our rotation, so we don't warp the arrow around when it's time to rotate. A good value to start with might be 360f, 360 degrees per second. Try experimenting with different values to find one that you like:
public float maxRotationSpeed;
The update procedure
In Update, determine the direction to the target:
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
Then, we need to know where the arrow is currently pointing. We can use Transform.TransformVector to find where the local localArrowDirection is pointing in world space:
Vector2 currentDirection = transform.TransformVector(localArrowDirection);
Then, determine the signed angle from boundaryDirectionLeft to the target direction, the same from boundaryDirectionLeft to boundaryDirectionRight, and the same from boundaryDirectionLeft to the current facing direction:
float directionAngle = Vector2.SignedAngle(boundaryDirectionLeft, direction);
float boundaryAngle = Vector2.SignedAngle(boundaryDirectionLeft, boundaryDirectionRight);
float currentAngle = Vector2.SignedAngle(boundaryDirectionLeft, currentDirection);
These values range from [-180,180], but we want them expressed in the range [0,360) to make the math easier later, so we can add 360f and use Mathf.Repeat on that sum:
directionAngle = Mathf.Repeat(directionAngle+360f, 360f);
boundaryAngle = Mathf.Repeat(boundaryAngle+360f, 360f);
currentAngle = Mathf.Repeat(currentAngle+360f, 360f);
At this point directionAngle is how many clockwise degrees from boundaryDirectionLeft that target is, and boundaryAngle is how many boundaryDirectionRight is, and currentAngle is the same for what direction we're currently facing.
So, now, we need to know how to properly clamp the angle between 0 and boundaryAngle. Anything too far above boundaryAngle is actually closer to the left boundary and should be clamped to the left boundary. In fact, since everything is between 0 and 360, anything higher than boundaryAngle+(360f-boundaryAngle)/2f is closer to the left. So, we just set anything higher than that to be 0 degrees away from boundaryDirectionLeft:
if (directionAngle > boundaryAngle + (360f - boundaryAngle)/2f)
{
directionAngle = 0f;
}
So, now we can clamp directionAngle with a high of boundaryAngle (it is already bottom clamped at 0f, so we can use Mathf.Min here):
directionAngle = Mathf.Min(directionAngle, boundaryAngle);
Now we can limit the angular difference between directionAngle and currentAngle using our maxRotationSpeed:
float deltaAngle = Mathf.Clamp(directionAngle-currentAngle,
-maxRotationSpeed * Time.deltaTime,
maxRotationSpeed * Time.deltaTime);
Now we can rotate the transform deltaAngle degrees clockwise (in world space):
transform.Rotate(0f,0f,deltaAngle,Space.World);
I have a ai (the red circle) which should shoot at my player (the blue circle).
Currently i'm using a normal Raycast:
Ray ray = new Ray(transform.position, transform.forward);
which gives me the purple Line.
Now, when there is a corner (like on the image), it doesn't hit the player, but it could if it would shoot a bit more to the side.
I've seen a solution for this by adding an angle to that raycast, but this doesn't work for me, because the angle is different if the player is near or far away from the ai.
What i need is:
That the ai shoots a raycast from itself to the side (left & right) of the player, but i don't know how to do that.
Your player certainly has some kind of radius, no?
Just using the distance between the player and the shooting AI, the player's radius and some nice trigonometry, you should be able to generate two rays to test both if the shooting AI sees the player's "right side", as well as his "left side".
Vector3 direction = player.transform.position - shootingAI.transform.position;
float distance = direction.magnitude;
float playerRadius = player.radius;// this is a variable you need to set
float angleToRotate = Mathf.Atan(radius/distance); // trigonometry: tan(angle)=oppositeSideLength/adjacentSideLength
Vector3 rayDirection1 = Quaternion.Euler(0f, -angleToRotate, 0f) * direction;
Vector3 rayDirection2 = Quaternion.Euler(0f, angleToRotate, 0f) * direction;
Using these two rays as directions you should be testing for the "right side", and the "left side"
You can find good answer HERE.
Or maybe use Sphere Raycast and use Contact Point and shot at this point.
I have the following model. I'm moving it on the screen by changing the transform.position. The problem is I want it to always point with the sphere to the direction it's moving to. How can I keep it always pointing there?
What about something like this?
Vector3 previousPosition = transform.position;
transform.position = … // your code
transform.LookAt(transform.position + (transform.position - previousPosition));