- Home /
Click to move player while avoiding jitter at edges
I have a question. I'm trying to build a faux gravity system and apply it to a CUBE planet instead of a sphere planet. I already made it work using 6 different triggers for each face of the planet so the player can stick to the cube planet's gravity by applying a force downwards relative to the player's transform.up. The question is, I'd like to use Ray casting to move the player to mouse position after mouse input, instead of horizontal or vertical axis inputs. Unfortunately, when I try this, it's only moving on the upper part of the cube and not really reaching the side faces. The player starts to stutter its movement when close to the edge (I imagining it is trying to reach the target position ignoring collision on a direct line), any ideas how could I fix this? Thanks in advance.
here is the code:
public class MovementTrhoughMouseCommand : MonoBehaviour { public float speed = 10f; public Vector3 targetPos; public bool isMoving = false; public LayerMask whatIsWorld; //Rigidbody rb;
// Use this for initialization1
void Start()
{
//rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SetTargetPos();
}
if(isMoving == true)
{
MoveObject();
}
}
void SetTargetPos()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000, whatIsWorld.value))
{
targetPos = hit.point;
isMoving = true;
}
}
void MoveObject()
{
//transform.LookAt(targetPos);
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, targetPos) <= 0.5f)
isMoving = false;
Debug.DrawLine(transform.position, targetPos, Color.red);
}
}