Inssue with 'transform.forward" unity - c#

I'm trying to make some point forward of my player camera, the problem is the point isn't forward of my camera, is very crooked.
Here it's clear the diference of the point to the camera forward.
I realy don't know what is causing this problem.

You are treating a direction as if it was a position
instead of
aimargetInstantiate.transform.position = cameraHolderObj.transform.forward * 10;
you rather want to use
aimargetInstantiate.transform.position = cameraHolderObj.transform.position + cameraHolderObj.transform.forward * 10;
Btw side note: To make your code a bit shorter and easier to maintain you can use
aimLayerAnimator.SetBool("IsAiming", isAiming);
and same in
isAiming = Input.GetKey(aimingKey);
;)

Related

How can I balance a cube with a rigidbody in unity

I am trying to have a cube rotate itself back to its orginal rotaion whenever the palyer bumbs in the cube but I don't want it to snap back instantly, I am trying to let it balance itself out and make it look jiggly but I do not how how to make it. I tried differnt ways but none of them work. This is my last try and I know that it is just checking one axis and so but I am clueless so can anybody tell me how to do this.
if(transform.rotation.z > 10)
{
transform.rotation = Quaternion.Slerp(transform.rotation, StartRot, TimeCount);
TimeCount = TimeCount + Time.deltaTime;
print("Go");
}
I would suggest looking at this first, and there are plenty of tutorials like this though that one is about a punching bag the concept is similer.

#Unity Cube Movement (Jumping +1 Forward/Right/Backward/Left)

Hey stackoverflow Community,
First of all:
I'm still very new about programming with C# and Unity.
My question:
I'm working on an idea for a Movement of a Cube.
It is planned that the cube will move forward by pressing a key (W-Key). But it shouldn't just move forward. It should jump forward to the next point. So always plus 1 of its axis into which it should go. Accordingly, it is only intended to go forward, right, down, left. He won't be able to jump over behind. You should also see that the cube jumps in the respective direction, so it should not teleport itself. :D
Does anyone have an idea how I can realize this movement?
I am very much looking forward to your ideas.
(Sorry if my English is not so good, my English not the best. ^^)
best regards
xKarToSx
So, in order to understand movement, it's best to first understand Vectors in Unity. Since you want to be moving the cube in the forward direction, I'm going to assume this is a 3D game, in which case you want to use a Vector3.
A Vector3 has three components: X, Y, and Z. Each component is tied to an axis. In simple terms, X is tied to left and right, Y is tied to up and down, and Z is tied to forward and back. So, Vector3 position = new Vector3(0, 1, 2); will be a vector that is 1 unit above and 2 units in front of the starting position.
Assuming you've attached this script to the cube you want to move, you can track its position with transform.position. So, if you want to move the cube one unit forward, your code would look something like this:
if(Input.GetKeyDown(KeyCode.W)) // This code will activate once the user presses W.
{
transform.position += new Vector3(0, 0, 1);
}
That will move the cube one unit forward in the Z direction. However, you don't want it to teleport, you want to see it move, correct? In that case, you want to check out Unity's Vector3.Lerp function. Basically, you would use it to smoothly transition an object between two defined positions. You'll need to implement a timer and a for loop in order to make this work correctly.
So, to summarize, for moving one unit forward in the Z direction, your code would look something like this:
if(Input.GetKeyDown(KeyCode.Z))
{
float startTime = Time.time; //Time.time is the current in-game time when this line is called. You'll want to save this to a variable
float speed = 1.0f; //The speed if something you'll want to define. The higher the speed, the faster the cube will move.
Vector3 startPosition = transform.position; //Save the starting position to a different variable so you can reference it later
Vector3 endPosition = startPosition + Vector3.forward; //Vector3.Forward is equivalent to saying (0, 0, 1);
float length = Vector3.Distance(startPosition, endPosition); //You'll need to know the total distance that the cube will move.
while(transform.position != endPosition) //This loop while keep running until the cube reaches its endpoint
{
float distCovered = (Time.time - startTime) * speed; //subtracting the current time from your start time and multiplying by speed will tell us how far the cube's moved
float fraction = distCovered / length; //This will tell us how far along the cube is in relation to the start and end points.
transform.position = Vector3.Lerp(startPosition, endPosition, fraction); //This line will smoothly transition between the start and end points
}
}
I hope this helps you. This is my first time answering a question so sorry if I got some things wrong/it's not the most optimized. Good Luck!

Can`t throw an object aligned with vertical angle of the camera with .velocity = transform.TransformDirection( Vector3.forward)

I made a script for throwing a grabbed object, but i don`t know how to make it so the object is being launched depending on the vertiacal angle of the camera, not just forward. What paramentr should i give to the TransformDirection? Here is the code
void throwObject(float pushForce){
carrying = false;
carriedObject.GetComponent<Rigidbody> ().velocity = transform.TransformDirection(Vector3.forward * pushForce);
carriedObject.gameObject.GetComponent<Rigidbody> ().useGravity = true;
carriedObject = null;
}
You would want to take into account the camera's X rotation. So, something like:
carriedObject.GetComponent<Rigidbody> ().AddForce(
(Vector3.forward * pushForce) + (Vector3.up *
-Camera.main.transform.rotation.eulerAngles.x));
Firstly, how this should work: X, in most cases, should be the axis at which the camera is able to look "up and down." If it's not, change it to whatever axis the camera rotates on to look up and down. By checking the X rotation of the camera, we get it's angle. Then, we make it negative, because by default a positive rotation on a camera is actually looking down. You also just might want to encapsulate
(Vector3.forward * pushForce) + (Vector3.up *
-Camera.main.transform.rotation.eulerAngles.x)
with a transform.TransformDirection() statement so that you can be at any rotation. It might not be necessary, but I'm not quite sure.
Secondly, it's a better idea to use Rigidbody.AddForce() than directly setting Rigidbody.velocity, or so I hear.
I hope this helped you out :)

Looking for a good way to handle tile based corner-collisions

Okay so, i have a tiled map (obviously) and implemented a collision detection system which is working really well for me. It has trouble with those pesky corners though. I do know why that is, since i don't even check the corners. And that's the point, i don't know how to do that. So, first of all here is my current code:
Body body = currentObject.Body; // Body is a class storing position, velocity, bounds and so on.
int tileDimensions = level.TileWidth; // Since the tiles are squares...
int leftTile = body.Bounds.Left / tileDimensions;
int topTile = body.Bounds.Top / tileDimensions;
int rightTile = (int)Math.Ceiling((float)body.Bounds.Right / tileDimensions - 1);
int bottomTile = (int)Math.Ceiling(((float)body.Bounds.Bottom / tileDimensions) - 1);
if (body.Velocity.Y > 0) // Moving down.
{
for (int x = leftTile; x <= rightTile; x++)
{
for (int y = bottomTile + 1; y <= (bottomTile + 1) + (body.Velocity.Y / tileDimensions); y++)
{
if (tiles[x, y] != null && !tiles[x, y].IsPassable)
{
newVelocity = new Vector2(body.Velocity.X, MathHelper.Clamp(body.Velocity.Y, 0, tiles[x, y].Body.Bounds.Top - body.Bounds.Bottom));
body.Velocity = newVelocity;
break;
}
}
}
}
So thats just for moving down. There are 3 other constructs like that for up, left and right. The only real difference is the loop and the way i clamp the velocity.
As you can see i just loop through all tiles i could potentially collide with. Then i clamp the velocity, which will slow it down in case there is indeed a tile in it's way.
Now, i'm afraid it's hard to explain my problem with just words, so i'll have to post a picture too.
In this screenshot yellow means unpassable tile, black are the tiles the above code is currently checking for collision and red is the player.
To show you what the problem is, imagine i were to accelerate up and right in this frame. As you can see, there would be a collision with the tile on the upper right of my player but the player will just move into the tile since i don't check it for collision. And i will not check it in the next frame either, since i don't check for blocks i'm in because ... i don't even know, that would betray the whole idea behind my code, wouldn't it ? :P
Of course, i could just extend my "searching" range, but then i would collide with tiles, i shouldn't collide with.
Currently, i'm fixing this with an extra check for all the tiles my bounds are overlapping with and... you know, just moving the player back if i find any. But this is really messy and it doesn't preserve the initial velocity. If the player hits a corner he will move into it, i will detect that, move him back and null his velocity. That just doesn't feel right, it's clunky.
I just can't seem to figure out a good way of dealing with such cases. I doesn't happen too often (since it's really hard to reproduce) but once in a while it happens and that is of course unacceptable.
I'd really like to not even have a bugfix-type thing for it but to integrate it in my other code as nicely as possible. This is not mandatory, but it would be cool to be able to do that.
So i'd really appreciate if anyone of you guys could throw something at me.
Anyway, i hope you were able to follow what i was trying to say. Since english isn't my native language it's a little hard to explain such things at times. Also i'm just really bad at explaining things :/
I suppose you could just add 4 more cases, handing when the currentObject is moving in a diagonal, no?
However, you might want to investigate collision based on bounding volumes.

How do I transform Vector3s using a world Matrix properly?

I thought it would be simple as:
Vector3 point = Vector3.Transform(originalPoint, worldMatrix);
But apparently not... It make's the point's numbers shoot into the thousands.
Basically, what I'm trying to do is creating a collision system and every two points in this system is a line, so basically I want to collide lines. I want the lines to be able to scale, rotate, and translate based on a world matrix (so that the collision lines are in tune with the object's scale, rotation, and translation).
I've been trying for hours now and I can't seem to figure it out. I've tried multiplying by the View Matrix as well and while that is the closest to what I want, it seems to switching between two sets of numbers! It would be perfect if it stayed with the one set, I have no idea why it keeps changing...
Any help, please? :(
Edit: To add a little, I'm constantly updating the points in an Update call. But I don't know if that would change anything, either way the points = originalpoints first.
Steve H:
One line would have two points, so:
originalPoint[0] = new Vector3(-42.5f, 0f, 0f);
originalPoint[1] = new Vector3(42.5f, 0f, 0f);
point[0] = Vector3.Transform(originalPoint[0], worldMatrix);
point[1] = Vector3.Transform(originalPoint[1], worldMatrix);`
At first, point[0] & [1] equals the same as originalPoint[0] & [1]. But, the moment I move my player even just a few pixels...
point[0] = (-5782.5f, 0f, 0f)
point[1] = (-5697.5, 0f, 0f)
The player's position is -56.0f.
My worldMatrix goes as:
_world = Matrix.Identity // ISROT
* Matrix.CreateScale(_scale) // This object's scale
* Matrix.CreateFromQuaternion(_rotation) // It's rotation
* Matrix.CreateTranslation(_offset) // The offset from the centre
* Matrix.CreateFromQuaternion(_orbitRotation) // It's orbit around an object
* _orbitObjectWorld // The object to base this world from
* Matrix.CreateTranslation(_position); // This object's position
The objects display properly in graphics. They scale, rotate, translate completely fine. They follow the orbit's scale, rotation, and translation too but I haven't tested orbit much, yet.
I hope this is enough detail...
Edit: Upon further research, the original points are also being changed... :| I don't get why that's happening. They're the exact same as the new points...
I figured out my problem... -_-
So, after I create the line points, I do this at the end:
originalLines = collisionLines;
collisionLines & originalLines are both Vector3[] arrays.
I guess just by making one equal the other, it's like they're the exact same and changing one changes the other... that is something I did not know.
So I made this function:
void CreateOriginalPoints()
{
_originalPoints = new Vector3[_collisionPoints.Length];
for (int i = 0; i < _collisionPoints.Length; i++)
_originalPoints[i] = _collisionPoints[i];
}
And this solves the problem completely. It now makes complete sense to me why this problem was happening in the first place.
Thanks a lot Donnie & Steve H. I know you two didn't answer my question but it got me to poke around even deeper until I found the answer.

Categories