- Home /
Raycasting in direction of input, while player's gravity is relative to the surface they are standing on?
I am using a script for my player similar to this one made by @aldonaletto (C# version by @getyour411): http://answers.unity3d.com/questions/155907/basic-movement-walking-on-walls.html
However, the collision with walking into walls is quite buggy and the player is able to even pass through some of these colliders.
What I would like to do is raycast in the direction of the directional inputs to see if there is a collider in the way, (the raycast being the length of the player's width) and if there is a collider in the way, it will not allow the player to continue moving in that direction.
I am having trouble figuring out how to raycast in the input's direction while also having the player's rotation constantly changing because gravity is relative to the surface the player is standing on.
This is the code I have for movement input:
leftInputHorizontal = Mathf.Clamp(controller.LeftStickX + Input.GetAxis("Horizontal"), -1f, 1f);
leftInputVertical = Mathf.Clamp(controller.LeftStickY + Input.GetAxis("Vertical"), -1f, 1f);
The way that the player's normal is found is (from aldonaletto/getyour411's code):
Ray groundedRay;
RaycastHit groundedHit;
// update surface normal and isGrounded:
groundedRay = new Ray(myTransform.position, -myNormal); // cast ray downwards
if (Physics.Raycast(groundedRay, out groundedHit))
{
// use it to update myNormal and isGrounded
isGrounded = groundedHit.distance <= distGround + deltaGround;
surfaceNormal = groundedHit.normal;
}
else
{
isGrounded = false;
}
myNormal = Vector3.Lerp(myNormal, surfaceNormal, lerpSpeed * Time.deltaTime);
I have a feeling that it would have something to do with the Vector3.Cross function, but I can't seem to figure it out...
Answer by Igor_Vasiak · Apr 28, 2017 at 04:35 PM
Movements that are not based on physics get a little messy at a physics game. Use Rigidbody.AddForce() instead. Just like this: private float speed = 120000;
private float inputV;
private float inputH;
private float moveZ;
private float moveX;
private Rigidbody rbody;
void FixedUpdate
{
rbody = GetComponent<Rigidbody>();
inputV = Input.GetAxis("Vertical");
inputH = Input.GetAxis("Horizontal")
moveZ = inputV * speed * Time.fixedDeltaTime;
moveX = inputH * speed * Time.fixedDeltaTime;
rbody.velocity = new Vector3(0, rbody.velocity.y, 0);
if (inputV != 0)
rbody.AddForce(transform.forward * moveZ * Time.deltaTime, ForceMode.Force);
if (inputH != 0)
rbody.AddForce(transform.right * moveX * Time.deltaTime, ForceMode.Force);
}
Just make sure It's on FixedUpdate loop, since it run almost the same time as physics calcules. Hope I've helped.
Thanks for the help! I was using transform.Translate to move and I guess that doesn't work well with the rigidbody, so I'll use your method now! :)