- Home /
Get set of Pixels from PolygonCollider2d Position
Hello, This is my first question so I apologize in advance if I break any rules.
I am using the Unity 4.3.4, 2D project.
I'm working on a piece of code that gets triggered when a "Shot" hits a "Mountain". What I want to achieve is the Shot creating a crater in the Mountain. I have a CircleCollider2d on the Shot and a PolygonCollider2d on the Mountain. I am entering when the event occurs with the following code, which is working fine:
void OnTriggerEnter2D(Collider2D otherCollider)
{
//Check if our Shot hit the Mountains
if (otherCollider.name == "Mountains")
{
deformPixels(otherCollider.gameObject,gameObject.transform.position);
}
Destroy (gameObject);
}
The problem comes from the deformPixels function. Right now I have the following:
void deformPixels(GameObject land, Vector3 position)
{
Vector2 hitPos = new Vector2 (position.x, position.y);
hitPos = convertToLocal(land.transform, hitPos);
//Get the SpriteRenderer on the Mountains
SpriteRenderer sr = land.GetComponent<SpriteRenderer> ();
if (sr != null)
{
//Size of the Texture
Rect spriteRect = sr.sprite.textureRect;
Vector2 landScale = new Vector2(land.transform.localScale.x,land.transform.localScale.y);
//Adjusted Dims:
// dimension of the instantiated sprite?
// Get this by multiplying the instantiated Scale and the texture dimensions.?
// Not sure if this is correct...
Vector2 adjustedDims = new Vector2(spriteRect.width * landScale.x,spriteRect.height * landScale.y);
Debug.Log("SpriteRect = " + spriteRect + " Scale = " + landScale + " Adjusted Dims = " + adjustedDims + " HitPos = " + hitPos);
Texture2D tex = sr.sprite.texture;
Vector3 localPos = land.transform.InverseTransformPoint(position);
Vector2 texturePos = new Vector2(localPos.x, localPos.y);
texturePos.x = texturePos.x * tex.width;
texturePos.y = texturePos.y * tex.height;
Debug.Log("Texture Pos = " + texturePos);
texturePos.x = texturePos.x / spriteRect.width;
texturePos.y = texturePos.y / spriteRect.height;
Debug.Log ("Texture Pos = " + texturePos);
}
}
The following is list of psuedo steps that I believe need to happen.
/*
Psuedo-psuedo:
1. Get location of The shot on the Mountain
2. Convert that location into texture coordinates of the Mountain
3. Grab a portion of Pixels from the Mountain Texture based on were the shot lands
4. Remove a subset of the grabbed pixels
5. Re-write those pixels to the instantiated sprite
6. Remove / Re add PolygonCollider2d to update collider
*/
I don't believe that I am doing this correct since my Mountain texture is 640X400 and the Scale is X = 3.4, Y = 3.4 Yet I am getting positions of + and - 2000 on the X axis. Which is Double what I would expect (3.4 * 640 / 2 = 1088 in + or - direction).
So far I can get the location of the hit on the mountain. I guess the most immediate thing that needs to happen is getting the location of the hit on the texture, so then I can get the set of pixels on the texture.
I have attached some screen shots: