Freezing Movement to the side after rotating GameObject - unity3d

I am trying to freeze the position of a GameObject towards the z-Axis but when turning the GameObject the z-Axis should turn with it (or atleast the freeze Position)
So basically I want my object to only be able to move forward, backwards and up and down, no matter what direction it is facing.
A RigidBody freeze Position is in relation to the world axis and not the rotated axis of the object.
Appreciate the help, thank you
Top Down View of Object, before rotation and after

You can get the GameObject's "z-axis" with transform.forward. If this isn't the axis you want, try transform.right or transform.up.
It's unclear what you're asking for. Here are two cases that might answer your question:
To confine velocity to the "z-axis":
//reference to the Rigidbody to restrict
private Rigidbody rig;
void Start(){
//find the Rigidbody attached to this GameObject
rig = GetComponent<Rigidbody>();
}
//Updates every physics frame
void FixedUpdate(){
//set the velocity to the component of the velocity that is parallel to the forward direction
rig.velocity = transform.forward * Vector3.Dot(transform.forward, rig.velocity);
}
If you don't want any movement in the "z-axis", replace the rig.velocity = ... line with rig.velocity -= ...
Put this code in a MonoBehaviour (script) attached to your GameObject.
Note that if the GameObject is physically hit, it might spin, causing the "z-axis" to rapidly change. To prevent this, you could use the Rigidbody freeze rotation.

Related

How can I prevent non-trigger colliders from pushing each other in Unity?

I got pre-made projectiles from the Unity's asset store and couldn't figure out a way to make them work my intended way.
The projectiles have colliders (not triggers), rigidbody and a script that moves them by .velocity. It detects a collision using OnCollisionEnter, making them push objects that have rigidbodies (behavior not wanted).
I could indeed use OnTriggerEnter, but the projectile spawns particles using the ContactPoint from the OnCollisionEnter method that OnTriggerEnter doesn't have access to. I tried to simulate this ContactPoint using raycasts, but no luck. Could rewrite the code from scratch, but only if there's no other way...
There's this video where the guy has the same setup as my projectile, rigidbody and collider, yet, the projectile doesn't push the other object, but he doesn't go deeper on its behavior.
Any ideas?
In Edit -> Project Settings -> Physics, you will find the Layer Collision Matrix at the bottom. Here you can choose which layers collide with which layers. The default layer for gameobjects is "Default". Assign a new layer to your projectiles and the gameobjects you don't want collisions with. Then you can uncheck the box that represents these two layers in the Layer Collision Matrix. Now these gameobjects will not affect each other when colliding and methods like OnCollisionEnter will not be called for them. Hope this answers your question fully.
You'll need to keep the velocity, angular velocity, and position every frame, then add some code to OnCollisionEnter in which you tell the two colliders to ignore each other from now on, and also restore the projectile's original velocity, angular velocity and position.
private Collider col;
private Rigidbody rigidBody;
private Vector3 vel;
private Vector3 angularVel;
private Vector3 position;
private void Start() {
col = gameObject.GetComponent<Collider>();
rigidBody = gameObject.GetComponent<Rigidbody>();
}
private void FixedUpdate() {
vel = rigidBody.velocity;
angularVel = rigidBody.angularVelocity;
position = transform.position;
}
private void OnCollisionEnter(Collision collision) {
Physics.IgnoreCollision(col, collision.collider);
rigidBody.velocity = vel;
rigidBody.angularVelocity = angularVel;
transform.position = position;
}

Unity 3D - Collisions

I have a problem with physics. It is my first time doing in 3D, so it may be just a beginner mistake.
I just wanted to create a simple player controller and make it so that it can not pass trough cubes.
The problem is that when going straight into the cube, part of the player is in the cube itself. When stop moving, it pushes me, so they are not intersecting (that makes sense).
I tried moving the player using .Transalte, .MovePosition and by changing the velocity of rigidbody itself. None of it change anything. The player can always move a part of him into the cube.
Any ideas how to solve this?
My player controller:
(The 2 lines commented out in Move() are just other ways to move the player.)
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float movementSpeed;
private Vector3 input;
private void Update()
{
GetInput();
}
private void FixedUpdate()
{
Move();
}
private void GetInput()
{
float inputHorizontal = Input.GetAxisRaw("Horizontal");
float intputVertical = Input.GetAxisRaw("Vertical");
input = Vector3.ClampMagnitude(new Vector3(inputHorizontal, 0, intputVertical), 1);
}
private void Move()
{
GetComponent<Rigidbody>().velocity += input * movementSpeed;
//GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + input * movementSpeed * Time.deltaTime);
//transform.Translate(input * movementSpeed * Time.deltaTime, Space.World);
}
}
Player is standing still
Player is moving towards cube
Settings of the Game Objects itself
Now I think I understand your problem.
The collider is a geometric shape that is checked but the outcome wont take place until the collision has actually taken place, this means, one geometric shape being inside the other. By this I mean, that what you are experiencing is the normal behaviour of the collision. If both elemnts are rigid bodies, both will move and your problem wont be perceivable, but if your cube is not a rigid body or is kinematic, will stand still in the same position, and depending on the other object speed, its normal that an invasion/superposition of the elements is perceivable, because that is the frame were the collision took place, and were your element needs to be moved back because it has collided.
Consider that if the speed is high enough, and the position from one frame to another varies enough, the collision might not even take place, because the geometric parts do not interfere between frames, as the position variation might be bigger than the bounds of the collider itself. The collision check at the end of the day, is dicrete, and not continuous (even you can set it as continuous to be as frecuent as possible).
To solve or improve that, you can adjust the speeds to avoid that being perceivable + adjust your collider to make it react before the graphic superposition occurs. This means making the capsule or the cube collider bigger than the graphic element itself. You can even calculate , to make it as bigger as much as your your speed * Time.deltaTime result or speed * FixedTimeStep result, depending on your safety distance needs. I think one of those should be the safety distance you need to take into account before the graphic collision occurs.
Another thing you can do is tight more the times physics calculations are done.
https://docs.unity3d.com/Manual/class-TimeManager.html
But need to be careful with this as this can be a performance devourer and need to be handled with care. You can make some trials with that and check your problem can improve.
Hope that helps
You can increase the scale of your player's collider from the Collider component attached to it. You can check how big the collider is from the editor scene view.
Edit: The issue might be that your movement or collision code is called in Update instead of FixedUpdate. When working with rigidbodies, you want to call the physics calculations inside FixedUpdate.
remove rigidbody from the cube, you can click on 'Gizmos' in the top right of the editor and make sure the colliders are at the edges of the objects.

Getting Rope To 'Swing'

I have bunch of Cylinders connected with Hinge joints, as per a youtube tutorial. Now the hinge joints move when an ExplosionForce is applied to them, but I want them to 'swing' back and forth when they are moved via the animation.
So I have the top Cylinder's RigiedBody set to Kinematic, and I animate that along the X axis to the right. Then it stops abruptly, and i want the bottom or the rest of the 'rope' to swing a bit further to the right then back again like a rope would. Ultimately I want to attach a spotlight to this rope and light up my scene. But I can't get the rope to swing, it just stays static.
I've exported the scene as a package, you can download it here:
https://www.pastefile.com/Up59SO
Here is an animation of the rope not swinging:
Please help. This is really annoying and I cannt see why it shouldnt be working!
Firstly make sure all rigidbodies are in the root of the scene; not parented to anything. Secondly, you have to use physics forces to get the elements to swing. However, you can't apply forces to kinematic objects. So what I would advise is instead of setting the root of the rope as kinematic to freezing its position on the Y axis.
public class Movement : MonoBehaviour
{
[SerializeField] Rigidbody rigidbody;
[SerializeField] float power = 25;
[SerializeField] float speed = 5;
void FixedUpdate()
{
rigidbody.AddForce(Vector3.right * Mathf.Cos(Time.time * speed) * power);
}
}
Maybe something like this could help, https://answers.unity.com/questions/1244519/how-to-randomly-set-the-direction-of-an-object-and.html?_ga=2.69603664.1732232616.1585344454-527098876.1571345094
Try thinking of it like wind.

Unity|Moving gameobjects away from other gameobjects which are moving towards them

I have 2 AI game objects which are both capsules. Considering the first capsule AI is named X and the second capsule AI is named Y, I try to make Y move away from X (escape from him) while X is chasing Y (following him). I have no idea how to do that, I would appreciate a direction.
I tried to do what's written here, but they both move through walls even though they have capsule collider, I tried to do this:
http://forum.unity3d.com/threads/getting-objects-to-move-away-from-my-users-gameobject.142468/
but they only move in one direction and through walls.
Vector3 position = transform.position;
Vector3 targetPosition = target.transform.position;
Vector3 direction = position - targetPosition;
transform.position += direction * 2.0f * Time.deltaTime;`
You are moving them with transform.Translate. Moving the transform means "Put the object at the given position regardless of environment". If you want them to interact, you need to either use the CharacterController component and its methods or a rigidbody component and move it with force.

Unity - Inconsistant speed of object following raycast2D

So im creating a simple game and one component of the game is a greendot following the outside of the level. I got this working using a raycast in the middle which rotates and gives the position of collision the the gameobject.
game overview
The problem is that the speed is inconsistant at the moment since the distance between two collisions can be further distance if i have a slope. I also have the feeling that there should be a easier way to get the same result. What are your thoughts?
public class FollowPath : MonoBehaviour {
Vector3 collisionPos;
public GameObject greenDot;
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
transform.Rotate(0.0f, 0.0f, 3);
if (hit.collider != null)
{
collisionPos = hit.point;
}
greenDot.transform.position = collisionPos;
}
}
I'm not sure if you will like this answer, as it suggests a complete departure from the way you were trying to do it.
A simple way to do this, would be to give your moving dot GameObject a Rigidbody2D component, AND a CircleCollider component.
Then, make your walls, and add to each an EdgeCollider component.
You'll probably also want to add a PhysicsMaterial2d to each GameObject with a Collider and set the friction and bounciness values for each.
Once this is setup, you can apply an initial force to the rigid body ball to get it moving, and it will bounce off the walls just like a ball does, using the Unity physics engine. No code would be needed in you update functions.