I want my player character (the feet ) to stick to the platform (like in the photo) rather than falling or following the physics. I want it to move like a spider but I am stuck.
With the help of this site, I was able to get to find the solution of my problem to get the following result.
Now I have this code and I cannot get it working because of my less understanding of the whole process. The script is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerRays : MonoBehaviour
{
public float distance;
public RaycastHit2D leftHitInfo;
public RaycastHit2D rightHitInfo;
public LayerMask layer;
public float offset;
public bool rayCastThrown;
public float maxRotationDegrees;
public float positionOffsetY;
bool doubleRaycasts (Vector2 rightOffSet, Vector2 leftOffSet) {
return Physics2D.Raycast (rightOffSet, Vector2.down, distance, layer) && Physics2D.Raycast (leftOffSet, Vector2.down, distance, layer);
}
void PositionOnTerrain () {
Vector3 averageNormal = ( leftHitInfo.normal + rightHitInfo.normal ) / 2;
Vector3 averagePoint = (leftHitInfo.point + rightHitInfo.point) / 2;
Quaternion targetRotation = Quaternion.FromToRotation (Vector2.up, averageNormal);
Quaternion finalRotation = Quaternion.RotateTowards (transform.rotation, targetRotation, maxRotationDegrees);
transform.rotation = Quaternion.Euler (0,0, finalRotation.eulerAngles.z);
transform.position =averagePoint + transform.up * positionOffsetY;
Debug.DrawRay (transform.position, -averageNormal, Color.red);
}
void Update () {
Vector2 leftOffSet = new Vector2 (transform.position.x - offset, transform.position.y);
Vector2 rightOffSet = new Vector2 (transform.position.x + offset, transform.position.y);
leftHitInfo = Physics2D.Raycast (leftOffSet, Vector2.down);
rightHitInfo = Physics2D.Raycast (rightOffSet, Vector2.down);
rayCastThrown = doubleRaycasts (rightOffSet, leftOffSet);
Debug.DrawRay (leftOffSet , Vector2.down * distance, Color.yellow);
Debug.DrawRay (rightOffSet, Vector2.down * distance, Color.cyan);
PositionOnTerrain ();
}
}
I cannot get it to working at all and while it seems to be working sometime and I can only see the red line working sometime (very rarely). I cannot pin point the problem as I see no result at all. I cannot wrap my head around the part of Quaternions and after that as given in the above link.