- Home /
how to move around rigidbody2D's in scene?,how to drag around a rigidbody2D object?
I'm making a game called death simulator, and it is 2d, side view. i want to be able to drag around items, but i cant figure out how. and remember, this has to collide with surrounding objects, so it cant be transform.position. instead i want to use myRigidBody.MovePosition(newPosition).
Rigidbody.MovePosition Rigidbody.MoveRotation
this way i can move it around, and it will collide with everything. i also want to set it to kinematic when held, but dynamic when released could you please correct this script to help?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DragMouseMove : MonoBehaviour {
private Vector3 mousePosition;
private Rigidbody2D rb;
private Vector2 direction;
private float moveSpeed = 100f;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = (mousePosition - transform.position).normalized;
rb.velocity = new Vector2(direction.x * moveSpeed, direction.y * moveSpeed);
}
else {
rb.velocity = Vector2.zero;
}
}
}
the problem with this one is that it falls really slow, and it will go to wherever I'm clicking. i would like for it to be when i click on it and drag. please test this in game to see if it works and thank you!,I'm working on a game similar to people playground, and i want to be able to drag them around without using transform.poistion. instead i want to use the rigidbody to moove things around: myRigidBody.MovePosition(newPosition).
Rigidbody.MovePosition Rigidbody.MoveRotation
but i have no clue how. could you write or alter my script for me so that it works?
script:
{
private Vector3 mousePosition;
private Rigidbody2D rb;
private Vector2 direction;
private float moveSpeed = 100f;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = (mousePosition - transform.position).normalized;
rb.velocity = new Vector2(direction.x * moveSpeed, direction.y * moveSpeed);
}
else {
rb.velocity = Vector2.zero;
}
}
}
Your answer
