I want to create a pushing wall in a 3D game. Here's an example of pushing walls in Super Mario 64
Pushing Walls in Super Mario 64 (Video on Youtube)
So this is the look of my walls in the inspector
And this is the code attached to the pushing wall
public class PushingObstacle : MonoBehaviour {
private Vector3 startPoint; // the current position when loading the scene
[SerializeField]
private Vector3 endPoint; // the target point
[SerializeField]
private float forwardSpeed; // speed when moving to the end
[SerializeField]
private float backwardSpeed; // speed when moving back to start
float currentSpeed; // the current speed (forward/backward)
private Vector3 direction; // the direction the wall is moving
private Vector3 destination; // the target point
private Rigidbody obstacleRigid; // rigidbody of the wall
private void Start()
{
startPoint = transform.position;
obstacleRigid = GetComponent<Rigidbody>();
SetDestination(endPoint); // set the target point
}
private void FixedUpdate()
{
obstacleRigid.MovePosition(transform.position + direction * currentSpeed * Time.fixedDeltaTime); // start moving
if (Vector3.Distance(obstacleRigid.position, destination) < currentSpeed * Time.fixedDeltaTime) // set a new target point
SetDestination(destination == startPoint ? endPoint : startPoint);
}
private void SetDestination(Vector3 destinationPoint)
{
destination = destinationPoint;
direction = (destination - transform.position).normalized; // set the movement direction
currentSpeed = destination == endPoint ? forwardSpeed : backwardSpeed; // set the speed
}
}
So when the player moves to the wall and touches it just a little, the wall just flies away.
I could set the walls rigidbody on kinematic mode. But I want the wall adds a minimal force to the player when pushing him. How can I achieve both behaviours (not flying away and small force against the player)?
Edit:
And I can not set it to kinematic because when jumping on the top of the wall (cube), the player is not moved relative to the wall.