- Home /
Attaching Object to mouse
Hello,
I'm working on a RTS and I have some trouble getting the object move smooth. It's following the mouse correctly but very jumpy at some point.
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Physics.Raycast (ray, out hit, Mathf.Infinity);
if(hit.collider.gameObject.tag == "Ground"){
attachedObject.transform.position = new Vector3(hit.point.x,hit.point.y+3f,hit.point.z);
hittedGround = hit;
}else{
if(hit.collider.gameObject.tag == "layout" && transform.position!=hit.point){
attachedObject.transform.position = new Vector3(hit.point.x,hittedGround.point.y+3f,hit.point.z);
}
}
I'm using a Raycast to get the correct "y" of the terrain and saving that to be able when I hover over the object that I can still move it with the same "y". But it seems between hitting the terrain and the object its a bit jumpy, like it gets moved to the position and after that moved to the correct "y". It's just an annoying effect. Maybe someone can help me.
Are you using rigidbodies, and if so, are you in fixedupdate?
When i posted that i didn't use Rigidbodies and I used the Update. At the moment I attached a Rigidbody to be able to check for collisions and block the placement of the object. In the FixedUpdate the effect is even stronger. As long as Iam on the Object it seems fine, it is just when i move my mouse faster and get off and hit the ground again.
If I use it without a Rigidbody and Collider it is working a lot better, just checking will get a bit more complicated.
Does "layout" gameObject and "Ground" gameObject often have different Y values?
It was even jumping on flat ground. And layout has always the Y from the ground before. But it is updating a lot if u mean that. I'm not sure if my approach is good in any way, still tinkering a lot.
Answer by NecrosDk · Apr 06, 2014 at 05:09 AM
I would do it so that when you click the object initially you turn on a bool in a script attached to the object, that defines that it has been picked up. Then in that seperate script I would say if it is picked up, make the position = Input.mousePosition. Right now it looks like you're raycasting it even when it's already picked up, which means if you move the mouse too quickly during one frame, it will fall out of the raycast? Remember also to make sure that the object doesn't collide with anything else in the scene if it's not supposed to do that.
Thanks for the response, but since I have some pla$$anonymous$$us as well I have to check at some point for a new Y. I just removed the Collider for now which fixed it since Iam now hitting the ground mainly and I made sure that I filter some obstacles like "trees" where the cast breaks and jumps the object. But now I have to do quite some Raycasting to check if obstacles are underneath it or does someone have a better way of doing that ? I just know Physics.OverleapSphere which is quite performace heavy when called a lot and I think Im done with Colliders for that attached object.