Unity - how to use Vector2.Reflect() - c#

I have looked everywhere including the Unity documentation but cannot seem to find any good examples of how to use Unity's Vector2.Reflect() function. I am trying to use this to control the direction of the ball (in a 2D Breakout game) when it hits a wall. It takes 2 arguments (inDirection, inNormal) but I cannot seem to figure out how to use this. Any help would be appreciated.

Vector2 Reflect(Vector2 inDirection, Vector2 inNormal):
inDirection: black arrow
inNormal: red arrow
return output: green arrow

The inDirection should be the velocity of your ball and the inNormal should be the unit vector that is perpendicular to your wall.
Try putting this in your ball object:
void OnCollisionEnter(Collision collision)
{
Vector2D inDirection = GetComponent<RigidBody2D>().velocity;
Vector2D inNormal = collision.contacts[0].normal;
Vector2D newVelocity = Vector2D.Reflect(inDirection, inNormal);
}
NOTE: I cannot currently test that code, so it may need tweaking in terms of the names of things.

Related

A-Star Unity 2D: How to find vector2 coordinates of AI's current waypoint?

[Using A-Star project] Hi. So the problem is in the title basically. I have a top-down game in which the enemy should face the direction they're going. I've tried:
To calculate Enemy's force of it's RigidBody in FixedUpdate
To calculate the vector from enemy to target.
In the first instance Enemy changes its animation states too quickly, every fixed frame there's a new force applied (especially annoying when the AI is close to target).
In the second Enemy always faces its target ignoring any obstacles. It's wallhacking, if you will.
To solve this bastard I decided to find AI's current waypoint and I do not know how to do that. I've found steeringTarget method in A-Star's documentation, but I couldn't figure out how to implement it.
I would REALLY appreciate any help. Thanks in advance!
(steeringTarget method)
https://arongranberg.com/astar/documentation/dev_4_1_0_9f8b6eb7/class_pathfinding_1_1_rich_a_i.php#a399e2bebfc8dfaf4fd291f051ca486e6
For questions related to A* Pathfinding Project it may be better to ask on the developer forum.
But here's my experience using it.
Usually you start with a seeker.
public Seeker seeker;
Since pathfinding calculations are asynchronous you must register for an event that tells us when the path is ready.
seeker.pathCallback += OnPathComplete;
Somewhere in your code you call to search for a path.
seeker.StartPath(start, end);
When the path is ready you will get a Path object. It contains all of the points and vectors.
List<GraphNode> path;
List<Vector3> vectorPath;
You can use the built-in PathInterpolator to smooth out the movement.
When you get the new path pass the vector path to the interpolator.
interpolator.SetPath(path.vectorPath);
On FixedUpdate you need to interpolate and apply the movement.
interpolator.MoveToCircleIntersection2D(transform.position, 0.1f, GraphTransform.identityTransform);
var moveDir = (interpolator.position - this.transform.position).normalized;
// Apply moveDir to Rigidbody, or whatever.
So thanks to the guy that tried to help, but that was not it. I solved my problem this way.
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
So this is the vector that's needed. From this game object to the end of the waypoint. Your code may vary.
Vector2 force = direction * speed * Time.deltaTime;
And this is the variable that is needed. So we set the animator with force.x and force.y and this should work.
I hope I made this at least somewhat clear. But if not - ask away.

Attempting to add a Dash movement option using Unity and C#

I'm making a very simple platformer game, not to publish or anything like that but rather to experiment with Unity and C#, and I've been trying to make a dash mechanic. two ways that I tried to go about this were
Getting the players position and teleporting them in any one direction, depending on the direction of the dash, didn't work because I couldn't figure out how to find the player's position
Making the player move fast in any one direction, didn't work because of how the rest of the movement script works.
I would prefer to use the first option, does anyone know how to find the players location? I think I was able to find the transform position, but I didn't know how to use it since it was 3 values, x, y, and z, rather than one, and I didn't know how to only get 1. Thanks in advance!
Not a definitive answer, since this depends on the code you are using and i have not shown how to dash, there is a lot of camera code and i am not coding unity anymore, so guessing this out without tests seem wrong, i would recommend adding the code, but the first option is simple enough to an answer.
In the player script, use transform.position, this will not fail since all Unity GameObjects have a world position, and therefore a transform.
// not sure if i spelled correctly
public class Player: Monobehaviour {
/* ... */
void Dash () {
// transform.position is the current position as a 3D vector
var pos = transform.position;
// to access its x, y and z do this:
var x = pos.x;
var y = pos.y;
var z = pos.z;
}
}

Addforce won't knockback my player character

I'm trying to add knockback to my player, but he won't move. I know the function is correctly called and the if a statement is functional, as he will still take damage, but the player won't move at all.
Weirdly, if I put the addForce somewhere else (Like in the update() method), it will work, but not in this scenario.
Some help would be greatly appreciated
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
TakeDamage(-20, 21);
theRB.AddForce((collision.transform.position - transform.position).normalized * 100, ForceMode2D.Impulse);
}
}
Here is what the Rigidbody looks like if it helps:
Hey I think the issue here is with your use of
(collision.transform.position - transform.position)
I would instead calculate the direction using the contact point of the collision and save that in a Vector. Then normalize that vector and multiply by -1 to launch the player in the opposite direction. Here's some sample code:
Vector2 dir = collision.contacts[0].point - transform.position;
// Flip the vector and normalize
dir = -dir.normalized;
// Apply Force
theRB.AddForce(dir * 100, ForceMode2D.Impulse);
Ok, so I figured out the answer. The problem lies in the way I managed movement in my Movement() function. To create movement, I used this line :
theRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * playerSpeed;
Apparently, velocity doesn't really work well with AddForce, for reasons I am not capable of explaining, as my understanding of Unity is still limited. I'll need to figure out a better way to manage movement, and I'll edit this post once I figure it out in case someone made the same mistake as me.
EDIT : So, turns out I've been looking for weeks, and didn't find anything. My final solution was to use a LERP instead of Addforce(), and just forget about physics alltogether.

Collision/Trigger detection between two remote objects

Is it possible to have a script in a GameEngine script and have it check for collisions between two remote objects that are not connected to the GameEngine script, via Update() or OnTriggerStay()/OnColliderStay()?
My plan for this script is to detect situations such as putting out room that is on fire. My original plan was to have a collider around this room checking for fire particles, and if there are no more particles, the fire is out. If you have a better suggestion, please let me know.
I assume you are referring with linear motion. If so Ray Casting is the solution. Ray Casting is forming a line or vector from a specific point to another point in a 3D plane. The purpose of the ray (vector) is to determine if it intersects with any colliders or other game objects.
It can be simply used like,
void Update() {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
// parameters are origin, direction and length of the ray.
if (Physics.Raycast(transform.position, fwd, 10)){
print("There is something in front of the object!");
}
}
You can find more references and tutorials on the internet. Try Unity official tutorial on Raycasting

C# XNA Precise Collisions?

Hey guy's i'm making a Paddle/Pong game and right now i'm trying to find out how to do precise collision between my paddle and my ball.. Currently it is basic collision if ball hits left side set x speed and y speed.. etc but i want to figure out how to make it bounce of on a direction so to speak as illustrated below:
Is there any way to do this? any help would be most appreciated.
Your examples can be handled by negating the y speed and keeping the x speed.
Collisions between the ball and the corners of the paddle are more difficult. You need to find the exact collision point, then calculate the vector from the center of the ball to the collision point. And finally negate the speed along that axis while keeping the component in the direction of the orthogonal axis.
Beware of ghosting too. And by that I mean that the velocity of the ball can be great enough that there isn't any frame (or Update routine call) in which the ball actually intersects with the bat, so you wouldn't detect a collision. See my illustration. In it, the ball in two different frames did intersect with the bat, even though there was no direct intersection. The result of this will be that the ball went 'through' the bat and magically appeared on the other side.
To solve this problem, you can't use the position of the ball to calculate if there was an intersection, you need to calculate the difference between the old and new position of the ball each frame and see if that line (the difference) intersected with the bat at any point.
The easy way to solve this would be to consider the bat as a horizontal line, then you could do a simple line-line intersection check. If they intersect, there was a collision. The more complicated way would be to do a line/vector-rectangle intersection. The advantage of that would be that you would also be able to detect collisions with corners which are an important part of a pong/breakout game.
I know this wont be helpful in your current situation, but you can try using a already made physics engine like Farseer to handle those collisions for you very easily.
protected override void Update(GameTime gameTime)
{
ballrect = new Rectangle((int)ballpos.X, (int)ballpos.Y,
ball.Width, ball.Height);
paddlerect = new Rectangle((int)paddlepos.X, (int)paddlepos.Y,
paddle.Width, paddle.Height);
ms = Mouse.GetState();
paddlepos.X = ms.X;
if (ballrect.Intersects(paddlerect))
{
bhpaddle();
}
ballpos += ballvel;
if (ballrect.Y>= paddlerect.Y)
{
ballpos = new Vector2(400, 480);
bhpaddle();
ballpos += ballvel;
l--;
}
base.Update(gameTime);
}
public void bhpaddle()
{
ballvel.Y *= -1;
}

Categories

Resources