- Home /
Looking for a touch based rigidbody2d.moveposition advice
I am looking to use touch to drag a ball through my scene. I have found solutions that use transform, however the ball is able to move through walls. Fixes for that do not work well at all. Apparently the moveposition function will work, but I am having a horrible time trying to get it to work.
And yes I have searched the internet and unity forums for it and results werent entirely helpful.
Asking fro scripts usually get your question rejected by the moderators. I've approved yours, but don't complain if no-one helps you. You've said "fixes for that do not work" but you've given no insight into what you've tried and what's gone wrong.
Answer by saravanan-P · Jun 30, 2015 at 04:58 PM
Try this ...
var speed:float;
var target : Vector3;
var start : Vector3;
var temp: Vector3;
private var pos;
var self : GameObject;
var distanceToObject : float = 7.5;
var dragging : boolean = false;
var sprite:SpriteRenderer;
function Start()
{
start = transform.position;
pos = transform.position;
sprite=GetComponent(SpriteRenderer);
}
function Update ()
{
transform.position.z=0;
if(Input.GetMouseButtonUp(0))
{
if(dragging)
{
dragging = false;
}
}
if(dragging)
{
pos = Input.mousePosition;
pos = Camera.main.ScreenToWorldPoint(pos);
temp = this.transform.position;
transform.position = Vector3.Lerp(temp, pos, speed*Time.deltaTime);
temp.z=0;
}
}
function OnMouseEnter () {
Destroy(self.GetComponent(Rigidbody));
dragging = true;
}
So this has the right feel to it and I love that I can set the speed, this is working super well but for 2 things.
1) Dispite its location the sprite spawns on the bottom right
2) I can still push through objects
i cant understand your 1st point..
but, for 2nd.. yeah.. that hapens ... coz it has a rigidbody.. so it may react that way.. this way of mechanism, works only for certain games like "mmm finger" etc..
1) In the editor I have the sprite top middle, at start it moves to the bottom left
2) is there a way around this?
was your mouse at the bottom left?? coz it maybe facing towards it..
change that On$$anonymous$$ouseEnter() to On$$anonymous$$ouseDown()
and in function Start(), change the "sprite=GetComponent(SpriteRenderer);" to sprite=this.GetComponent(SpriteRenderer);
wat type of "way", are you expecting?
Your answer
![](https://koobas.hobune.stream/wayback/20220613201550im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Finding the centre of two touches 2 Answers
Stop Moving When Not Touching Screen? 1 Answer
Shoot Bullet At Touch Position : 2D 1 Answer
touch position to world position 2D 2 Answers