- Home /
How do I Control An Objects Movement Only On the X Axis and Have a RigidBody Control Movement on the Y axis?
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.
Answer by facePuncher7 · Mar 28, 2016 at 02:45 PM
At the end of PlayerMovement() add the line:
Mathf.Clamp(transform.position.x,leftpos,rightpos);
Your answer
Follow this Question
Related Questions
Rb2D.MovePosition not working - weird error... 1 Answer
slide and dash 2D 0 Answers
Issue with direction and rigibody2D 1 Answer
Vector2.MoveTowards and Rigidbody2D Velocity 3 Answers
Move car at same speed 0 Answers