- Home /
movePosition affects Velocity
Hello, I'm making a platformer, where you are jumping every time you touch a platform and you can drag your character with touch position. The problem is I'm using rigidbody's movePosition method to drag the player, but this affects the velocity that I'm setting, so my character could Jump. Every time I try to drag my player - the velocity.y freezes it's value as the last one before starting to drag. Any solutions?
Answer by UnitedCoders · Feb 01, 2018 at 12:58 PM
Share your code sample you are using to perform these functionality. to rectify your problem.
Answer by bobonik · Feb 01, 2018 at 01:46 PM
Here is my code, attached to the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float bounceForce;
private GameObject player;
private Rigidbody2D rb;
private Vector3 pos;
private Vector3 v3P1;
private bool movePlayer1;
private bool draggingP1;
private Ray ray;
private RaycastHit2D hit;
private Transform toDrag;
void Start()
{
player = this.gameObject;
rb = player.GetComponent<Rigidbody2D>();
draggingP1 = false;
toDrag = gameObject.transform;
}
private void Update()
{
pos = Input.mousePosition;
ray = Camera.main.ScreenPointToRay(pos);
if (Input.GetMouseButtonDown(0))
{
hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (hit && (hit.collider.tag == "Player1"))
{
//toDrag = hit.transform;
//dist = hit.transform.position.z - Camera.main.transform.position.z;
v3P1 = new Vector3(ray.origin.x, toDrag.position.y, 0);
v3P1 = Camera.main.ScreenToWorldPoint(v3P1);
//offset = toDrag.position - v3;
draggingP1 = true;
}
}
if (Input.GetMouseButton(0) && draggingP1)
{
movePlayer1 = true;
v3P1 = new Vector3(ray.origin.x, toDrag.position.y, 0);
//rb.MovePosition(v3);
}
if (Input.GetMouseButtonUp(0) && draggingP1)
{
movePlayer1 = false;
draggingP1 = false;
}
}
private void FixedUpdate()
{
if (movePlayer1)
{
rb.MovePosition(v3P1);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.relativeVelocity.y > 0f)
{
if (collision.gameObject.tag == "Platform")
{
Vector2 velocity = rb.velocity;
velocity.y = bounceForce;
rb.velocity = velocity;
}
}
}
}
Your answer
Follow this Question
Related Questions
Velocity powered rigidbody on a moving platform without parenting. 3 Answers
Move car at same speed 0 Answers
How do I make a sphere bounce forward without adding a lateral force? 1 Answer
unity bounce without physics 1 Answer
Unity 2D - Why does velocity causes the ball to change direction everytime it hits something? 1 Answer