How to freeze an GameObject on x axis in specific direction?
I've got a Raycast to the right of my GameObject (Player). When the laser hits something, I get Debug Messages. So now I want to freeze my Object to move more right, if the right Laser hits something (wall). How do I do this?
public class RayCasting : MonoBehaviour
{
void FixedUpdate()
{
//Length of the ray
float laserLength = 1f;
int layerMask = LayerMask.GetMask("Default");
//Get the first object hit by the ray
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, laserLength, layerMask, 0);
//If the collider of the object hit is not NUll
if (hit.collider != null)
{
//Hit something, print the tag of the object
Debug.Log("Hitting: " + hit.collider.tag);
}
//Method to draw the ray in scene for debug purpose
Debug.DrawRay(transform.position, Vector2.right * laserLength, Color.red);
}
}
Answer by epicpython · Aug 17, 2020 at 06:37 PM
Make sure that your object has a rigidbody, and then mess with the rigidbody constraints.
Documentation: https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.html?_ga=2.70639120.1030592926.1597686260-725683403.1597686260
Someone else asked a similar question(about freezing rotation instead of position), this might help: https://answers.unity.com/questions/38542/prevent-rigidbody-from-rotating.html#:~:text=You%20can%20check%20the%20checkbox,%2F%2F%20Freeze%20the%20rotation
This will keep your object from moving along the x-axis:
m_Rigidbody = GetComponent<Rigidbody>();
//This locks the RigidBody so that it does not move along x axis (can be seen in Inspector).
m_Rigidbody.constraints = RigidbodyConstraints.FreezePositionX;
Source: https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.FreezePositionX.html
When you say "Freeze my object to move more right", do you mean that you want it to be able to move to the left and not to the right? If so, my suggestion won't work, mine would just keep it from moving at all.
Thanks for your reply. I looked over the RigidBodyContstraints already, but it doesn't fit my needs. I wanna move it then to the left but not to the Right.