- Home /
How to change texture2d
I am trying to ray trace. I saw a few tutorials, but I do not need physics or anything really except the ability to change the color of a pixel in a given rectangular area. Quite simple actually, but the solution of simply changing the color of a pixel seems to elude me. My code makes a rectangle with green and magenta colors and is attached to the camera. I have tried many ways to force the pixels to change color and nothing works. Never mind what is the purpose of this code it evolved mostly around various attempts to change pixel colors. It is attached to the camera.
using UnityEngine;
using System.Collections;
public class RayTracer2 : MonoBehaviour
{
public Texture2D tex;
public int width;
public int height;
public float rayDistance;
public float t;
void Start ()
{
t = 1.0f;
width = 100;
height = 100;
//if (outTex) {
// Destroy(outTex);
//}
tex = new Texture2D(width, height);
Raytrace();
}
void update ()
{
int i;
t = t + 0.1f;
//Raytrace();
Color[] colors = new Color[width*height];
for(i = 0; i < width*height; i++)
{
colors[i] = Color.white;
}
tex.GetPixels(20,20,100,100);
tex.SetPixels(20,20,100,100, colors);
tex.Apply();
}
void OnGUI ()
{
//GL.PushMatrix();
//GL.LoadPixelMatrix();
GUI.DrawTexture(new Rect(20, 20, 200, 200), tex);
GUILayout.Label("fps: " + Mathf.Round(1/Time.smoothDeltaTime));
//GL.PopMatrix();
}
void Raytrace ()
{
int x, y;
Ray ray;
Vector3 RayPoint;
if (tex)
{
Destroy(tex);
}
tex = new Texture2D(width,height);
for (y = 0; y < 100; y += 1)
{
for (x = 0; x < 100; x += 1)
{
tex.SetPixel(x, y, Color.green);
ray = camera.ScreenPointToRay(new Vector3(x, y, 0.0f));
RayPoint = ray.GetPoint(6.0f*t);
if ((-5.0f < RayPoint.x) && (RayPoint.x < 5.0f))
{
if ((-7.0f < RayPoint.y) && (RayPoint.y < 7.0f))
{
if ((-6.0f < RayPoint.z) && (RayPoint.z < 6.0f))
{
tex.SetPixel(x, y, Color.magenta);
}
}
}
}
tex.Apply();
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613200248im_/https://answers.unity.com/themes/thub/images/avi.jpg)