- Home /
Possible to transform and objects position smoothly with confined movement dictated by raycasting, but controlled by user?
What I'm trying to create is a control scheme something along the lines of Boxi. Basically I have a sphere that the user will click on, and then drag in the direction they want the sphere to go. However that will have no bearing on the translation of the sphere. Instead the sphere is to calculate how far it is from the next collider and then automatically and smoothly animate towards that coordinate(confined to an axis) and stop before it actually collides with the wall. This is what I have to find the distance and re-position, but I'm not sure how to animate the transform smoothly:
var hit: RaycastHit; var smooth : int;
function Update (){ var horiz: float = Input.GetAxis("Mouse X"); var vert: float = Input.GetAxis("Mouse Y"); if(rigidbody.velocity.magnitude == 0){ if(Input.GetMouseButton(0) && horiz >= .5) { if (Physics.Raycast(transform.position, Vector3.right, hit)){ var distanceToRight = hit.distance; transform.Translate(Vector3(Mathf.FloorToInt(distanceToRight - .5),0,0)); } }if(Input.GetMouseButton(0) && horiz <= -.5) { if (Physics.Raycast(transform.position, -Vector3.right, hit)){ var distanceToLeft = hit.distance; transform.Translate(Vector3(Mathf.RoundToInt(-distanceToLeft + 1),0,0)); } }if(Input.GetMouseButton(0) && vert >= .5) { if (Physics.Raycast(transform.position, Vector3.forward, hit)){ var distanceToTop = hit.distance; transform.Translate(Vector3(0,0,Mathf.FloorToInt(distanceToTop - .5))); } }if(Input.GetMouseButton(0) && vert <= -.5) { if (Physics.Raycast(transform.position, -Vector3.forward, hit)){ var distanceToBottom = hit.distance; transform.Translate(Vector3(0,0,Mathf.RoundToInt(-distanceToBottom + 1))); } } } }
Should I write another script that has an Update function to transform the spheres position? I've tried and it doesn't seem to work properly.
Any insight would be greatly appreciated. Thanks! Dennis
Have you experimented with the Vector3.Lerp() function? It seems pretty useful in this case. You get the original position and the raycast hit position, then lerp the object to that position. Of course in your specific case you would need to calculate a distance of the wall to not collide with it. The only cons i can think now is that Lerp() does not include physics, so yous sphere would only slide. Such behavior would only be important in textured meshes, but you could use a UV animation too.
Your answer
Follow this Question
Related Questions
Player moves too fast and won't move to point 1 Answer
Enemy Animation to not stop when player runs out of range 1 Answer
Learning to move 1 Answer
Can I animate objects/cameras in Update() without breaking Physics.Raycast? 1 Answer
Controlling a rigged models muscle groups via script (C#) 0 Answers