- Home /
Can't figure out how to achieve an effect like QUBE
I saw this game recently and really liked it and I thought I could try porting it to Unity3D. http://www.youtube.com/watch?v=EoS2rSLOr_0
I can't figure out how to move the cubes to certain positions and not anywhere. Could you provide a C# script for it? Thanks in advance :)
P.S. I know how to implement the blue blocks using rigidbody.AddForce. I want to know the implementation of the red blocks.
Answer by Bunny83 · Mar 11, 2012 at 01:37 PM
Usually i don't write whole scripts for other people that are too lazy... In this case it's actually so simple that it took only a few min.
public class RedCube : MonoBehaviour
{
Collider m_Collider;
Transform m_Transform;
public float currentTarget = 0;
public float max = 3;
public float Speed = 1;
public float current = 0;
private float m_Offset;
void Start ()
{
m_Collider = collider;
m_Transform = transform;
m_Offset = m_Transform.localPosition.x;
}
bool CheckClick()
{
Ray R = Camera.main.ScreenPointToRay(Input.mousePosition); // mouse point
// Ray R = Camera.main.ViewportPointToRay(Vector2.one*0.5f); // screen center
RaycastHit hit;
return m_Collider.Raycast(R,out hit,10000);
}
void Update ()
{
if (Input.GetMouseButtonDown(0) && CheckClick())
currentTarget = Mathf.Min(currentTarget+1,max);
if (Input.GetMouseButtonDown(1) && CheckClick())
currentTarget = Mathf.Max(currentTarget-1,0);
if (current != currentTarget)
{
current = Mathf.MoveTowards(current,currentTarget,Time.deltaTime*Speed);
if (Mathf.Abs(current - currentTarget) < 0.01f)
{
current = currentTarget;
}
Vector3 pos = m_Transform.localPosition;
pos.x = m_Offset + current;
m_Transform.localPosition = pos;
}
}
}
I've tested the script without any FPS controller. Just with a fix camera so i changed the raycast to mouseposition instead of screencenter.
Don't forget to add a kinematic rigidbody to the cube if it should be able to push other things. Also you might have to implement some manual collision checks if two of these cubes can be pushed into the same space.
I am not home right now but I'll check the script ASAP. Thanks a lot :)
Works like a charm :) Thanks a lot. Could you please explain this line: // Ray R = Camera.main.ViewportPointToRay(Vector2.one*0.5f);
I don't get it...
$$anonymous$$y test project uses the mouse position. So it raycasts whereever you click with your mouse.
In QUBE you have a first-person-view and you usually aim with the some kind of crosshair at the screen center. Viewport coordinates goes from 0 to 1 (left to right or bottom to top). The screen center is at (0.5f, 0.5f). So i used the constant "one" which is the same as new Vector2(1,1)
and multiplied it with 0.5 so it gets new Vector2(0.5f, 0.5f)
.
Your answer
Follow this Question
Related Questions
Snap blocks that aren't cubes. 1 Answer
Performance While Loading Map 2 Answers
How do I make a block move to another blocks position 1 Answer
Pushable Blocks 3 Answers