I am trying to make a character for my game that can only be moved on the X axis by the player, but falls normally along the Y axis. As of right now as soon as I click my mouse the character shoots to the right of the screen and doesn’t fall at all. I also want to implement Mathf.clamp
to make sure that the player can’t leave the sides of the level as it does now but I’m not sure how to implment that in to my currently broken code. This is what it looks like so far:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public Rigidbody2D movePlayer;
private bool MouseClicked = false;
void Start () {
movePlayer = this.GetComponent<Rigidbody2D>();
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
MouseClicked = true;
}
if (MouseClicked == true) {
PlayerMovement();
}
}
void PlayerMovement() {
Debug.Log("Player Movement Initiated");
float mousePosInBlocksX = Input.mousePosition.x / Screen.width * 16;
Vector2 playerPos = new Vector2(mousePosInBlocksX, 0f);
Vector2 playerVel = new Vector2(mousePosInBlocksX, movePlayer.velocity.y);
movePlayer.MovePosition(playerPos);
movePlayer.velocity = playerVel;
}
}
Sorry if this is a simple beginners mistake.